#!/usr/bin/env python3
from pathlib import Path
import re
import shutil
import datetime
import subprocess
import sys

TARGET = Path("/home/pishvivy/social.pishibini.com/engine/football_league_live.php")

if not TARGET.is_file():
    print(f"ERROR: not found: {TARGET}")
    sys.exit(1)

text = TARGET.read_text(encoding="utf-8")

backup = TARGET.with_name(
    "football_league_live.php.backup_"
    + datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
)
shutil.copy2(TARGET, backup)
print(f"Backup: {backup}")

pattern = re.compile(
    r"""function leaguePersianName\(\s*
        string \$name,\s*
        string \$country,\s*
        \?string \$storedPersian = null\s*
    \): string \{\s*
    .*?
    \n\}""",
    re.S | re.X
)

replacement = '''function leaguePersianName(
    string $name,
    string $country,
    ?string $storedPersian = null
): string {

    /*
    |--------------------------------------------------------------------------
    | Central translation source
    |--------------------------------------------------------------------------
    |
    | football_leagues.persian_name is the ONLY Persian source.
    | AI worker/admin panel populate or edit that database field.
    | If it is still empty, safely fall back to the original API name.
    |
    */

    $storedPersian = trim((string)$storedPersian);

    if ($storedPersian !== '') {
        return $storedPersian;
    }

    return trim($name);
}'''

new_text, count = pattern.subn(replacement, text, count=1)

if count != 1:
    print(f"ERROR: expected to replace 1 leaguePersianName function, replaced {count}")
    sys.exit(1)

tmp = TARGET.with_suffix(".php.tmp")
tmp.write_text(new_text, encoding="utf-8")

check = subprocess.run(
    ["php", "-l", str(tmp)],
    text=True,
    capture_output=True
)

print(check.stdout.strip())

if check.returncode != 0:
    print(check.stderr.strip())
    tmp.unlink(missing_ok=True)
    print("ERROR: syntax check failed; original left unchanged.")
    sys.exit(1)

tmp.replace(TARGET)

print("Patched: leaguePersianName now uses DB persian_name only")
print("Fallback: original API league name when persian_name is empty")
print("DONE ✅")
