<?php
declare(strict_types=1);

require_once __DIR__ . '/config.php';

function mocker_sport_rapidapi_get(string $path): ?array
{
    $key = defined('SPORT_RAPIDAPI_KEY') ? (string) SPORT_RAPIDAPI_KEY : '';
    $host = defined('SPORT_RAPIDAPI_HOST') ? trim((string) SPORT_RAPIDAPI_HOST) : '';
    if ($key === '' || $host === '') {
        return null;
    }
    $path = $path !== '' && $path[0] === '/' ? $path : '/' . $path;
    $url = 'https://' . $host . $path;

    $ctx = stream_context_create([
        'http' => [
            'timeout' => 20,
            'header' => implode("\r\n", [
                'Accept: application/json',
                'x-rapidapi-key: ' . $key,
                'x-rapidapi-host: ' . $host,
            ]),
        ],
    ]);
    $raw = @file_get_contents($url, false, $ctx);
    if ($raw === false || $raw === '') {
        return null;
    }
    $j = json_decode($raw, true);

    return is_array($j) ? $j : null;
}

function mocker_sport_event_fetch_json(string $externalEventId): ?array
{
    $tpl = defined('SPORT_EVENT_PATH_TEMPLATE') ? (string) SPORT_EVENT_PATH_TEMPLATE : '/api/v1/event/{id}';
    $id = trim($externalEventId);
    if ($id === '') {
        return null;
    }
    $path = str_replace('{id}', rawurlencode($id), $tpl);
    if (!str_starts_with($path, '/')) {
        $path = '/' . $path;
    }

    return mocker_sport_rapidapi_get($path);
}

function mocker_sport_parse_event_result(array $data): ?array
{
    $finished = mocker_sport_detect_finished($data);
    $scores = mocker_sport_extract_ft_scores($data);
    if ($scores === null) {
        return null;
    }

    return [
        'finished' => $finished,
        'home' => $scores[0],
        'away' => $scores[1],
    ];
}

function mocker_sport_detect_finished(array $data): bool
{
    $enc = json_encode($data);
    if (!is_string($enc)) {
        return false;
    }
    if (preg_match('/"type"\s*:\s*"finished"/i', $enc)) {
        return true;
    }
    if (preg_match('/"status"\s*:\s*"([^"]*)"/i', $enc, $m)) {
        $s = strtolower($m[1]);

        return str_contains($s, 'finish') || str_contains($s, 'ended') || str_contains($s, 'complete') || $s === 'ft';
    }

    return false;
}

function mocker_sport_extract_ft_scores(array $data): ?array
{
    $pair = mocker_sport_try_home_away_scores($data);
    if ($pair !== null) {
        return $pair;
    }
    
    foreach ($data as $v) {
        if (is_array($v)) {
            $pair = mocker_sport_try_home_away_scores($v);
            if ($pair !== null) {
                return $pair;
            }
            $deep = mocker_sport_extract_ft_scores($v);
            if ($deep !== null) {
                return $deep;
            }
        }
    }

    return null;
}

function mocker_sport_try_home_away_scores(array $node): ?array
{
    $h = null;
    $a = null;
    if (isset($node['homeScore']) && is_array($node['homeScore']) && isset($node['homeScore']['current'])) {
        $h = (int) $node['homeScore']['current'];
    } elseif (isset($node['home']) && is_numeric($node['home'])) {
        $h = (int) $node['home'];
    }
    if (isset($node['awayScore']) && is_array($node['awayScore']) && isset($node['awayScore']['current'])) {
        $a = (int) $node['awayScore']['current'];
    } elseif (isset($node['away']) && is_numeric($node['away'])) {
        $a = (int) $node['away'];
    }
    if ($h !== null && $a !== null) {
        return [$h, $a];
    }

    return null;
}

function mocker_sport_parse_events_list(array $root): array
{
    $byId = [];
    mocker_sport_walk_for_events($root, $byId, 0);

    return array_values($byId);
}

function mocker_sport_walk_for_events(mixed $node, array &$byId, int $depth): void
{
    if ($depth > 30) {
        return;
    }
    if (!is_array($node)) {
        return;
    }
    $ev = mocker_sport_try_parse_list_event_row($node);
    if ($ev !== null) {
        $byId[$ev['id']] = $ev;
    }
    foreach ($node as $v) {
        if (is_array($v)) {
            mocker_sport_walk_for_events($v, $byId, $depth + 1);
        }
    }
}

function mocker_sport_try_parse_list_event_row(array $e): ?array
{
    if (!isset($e['id'])) {
        return null;
    }
    $id = trim((string) $e['id']);
    if ($id === '') {
        return null;
    }
    $homeName = mocker_sport_team_label($e['homeTeam'] ?? $e['home'] ?? null);
    $awayName = mocker_sport_team_label($e['awayTeam'] ?? $e['away'] ?? null);
    if ($homeName === '' || $awayName === '') {
        return null;
    }
    $startTs = null;
    if (isset($e['startTimestamp']) && is_numeric($e['startTimestamp'])) {
        $startTs = (int) $e['startTimestamp'];
    } elseif (isset($e['startTime'])) {
        $t = strtotime((string) $e['startTime']);
        $startTs = $t !== false ? $t : null;
    }
    $logoH = mocker_sport_team_logo($e['homeTeam'] ?? $e['home'] ?? null);
    $logoA = mocker_sport_team_logo($e['awayTeam'] ?? $e['away'] ?? null);

    return [
        'id' => $id,
        'homeName' => $homeName,
        'awayName' => $awayName,
        'startTs' => $startTs,
        'logoHomeUrl' => $logoH,
        'logoAwayUrl' => $logoA,
    ];
}

function mocker_sport_team_label($t): string
{
    if (!is_array($t)) {
        return '';
    }
    $n = trim((string) ($t['name'] ?? $t['shortName'] ?? $t['slug'] ?? ''));

    return $n;
}

function mocker_sport_team_logo($t): string
{
    if (!is_array($t)) {
        return '';
    }
    $u = $t['teamColors'] ?? null;
    if (is_array($u) && isset($u['logo']) && is_string($u['logo']) && $u['logo'] !== '') {
        return mocker_sport_normalize_logo_url($u['logo']);
    }
    foreach (['logo', 'image', 'crest', 'shirtUrl', 'avatar', 'picture', 'photo'] as $k) {
        if (isset($t[$k]) && is_string($t[$k]) && $t[$k] !== '') {
            return mocker_sport_normalize_logo_url($t[$k]);
        }
    }
    $nested = mocker_sport_find_logo_url_deep($t, 0);
    if ($nested !== '') {
        return $nested;
    }
    $tid = mocker_sport_team_numeric_id($t);
    if ($tid !== null && $tid > 0) {
        return mocker_sport_team_logo_proxy_url($tid);
    }

    return '';
}

function mocker_sport_team_numeric_id(array $t): ?int
{
    foreach (['id', 'teamId'] as $k) {
        if (isset($t[$k]) && is_numeric($t[$k])) {
            $n = (int) $t[$k];

            return $n > 0 ? $n : null;
        }
    }
    foreach (['team', 'participant', 'competitor'] as $nest) {
        if (isset($t[$nest]) && is_array($t[$nest]) && isset($t[$nest]['id']) && is_numeric($t[$nest]['id'])) {
            $n = (int) $t[$nest]['id'];

            return $n > 0 ? $n : null;
        }
    }

    return null;
}

function mocker_sport_normalize_logo_url(string $url): string
{
    $url = trim($url);
    if ($url === '') {
        return '';
    }
    if (str_starts_with($url, '//')) {
        return 'https:' . $url;
    }
    if (!str_starts_with($url, 'http')) {
        return '';
    }

    return $url;
}

function mocker_sport_team_logo_proxy_url(int $teamId): string
{
    if ($teamId <= 0) {
        return '';
    }

    return '/api/team_logo_proxy.php?id=' . $teamId;
}

function mocker_sport_find_logo_url_deep(array $a, int $depth): string
{
    if ($depth > 12) {
        return '';
    }
    foreach ($a as $k => $v) {
        if (is_string($v) && $v !== '') {
            if (preg_match('#^https?://#i', $v) && (
                preg_match('#\.(png|jpe?g|webp|svg)(\?|$)#i', $v)
                || stripos($v, 'image') !== false
                || stripos($v, 'logo') !== false
                || stripos($v, '/team/') !== false
            )) {
                return mocker_sport_normalize_logo_url($v);
            }
        }
        if (is_array($v)) {
            $x = mocker_sport_find_logo_url_deep($v, $depth + 1);
            if ($x !== '') {
                return $x;
            }
        }
    }

    return '';
}
