<?php
/**
 * Normalize Lichess broadcast URLs to PGN API and helpers for round import.
 *
 * @package Chess_Podium
 */

if (!defined('ABSPATH')) {
    exit;
}

final class ChessPodium_LichessRoundImport
{
    /**
     * Resolve a Lichess broadcast page or API URL to https://lichess.org/api/broadcast/round/{id}.pgn
     */
    public static function normalize_pgn_url(string $raw): string
    {
        $raw = trim($raw);
        if ($raw === '') {
            return '';
        }
        if (preg_match('#lichess\.org/api/broadcast/round/([a-zA-Z0-9_-]+)#i', $raw, $m)) {
            return 'https://lichess.org/api/broadcast/round/' . rawurlencode($m[1]) . '.pgn';
        }
        $parts = wp_parse_url($raw);
        $host = strtolower($parts['host'] ?? '');
        if ($host !== 'lichess.org' && $host !== 'www.lichess.org') {
            return '';
        }
        $path = trim($parts['path'] ?? '', '/');
        if ($path === '') {
            return '';
        }
        $segments = explode('/', $path);
        if (count($segments) >= 2 && strtolower($segments[0]) === 'broadcast') {
            $last = end($segments);
            if ($last !== '' && preg_match('/^[a-zA-Z0-9_-]{4,}$/', $last)) {
                return 'https://lichess.org/api/broadcast/round/' . rawurlencode($last) . '.pgn';
            }
        }
        return '';
    }
}
