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

TARGET = Path("/home/pishvivy/social.pishibini.com/engine/ai_gateway.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(
    "ai_gateway.php.backup_"
    + datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
)
shutil.copy2(TARGET, backup)
print(f"Backup: {backup}")

pattern = re.compile(
    r"""            case 'translate_names_batch':\n.*?(?=            case 'translate_text':)""",
    re.S,
)

replacement = '''            case 'translate_names_batch':

                return
                    "You are the canonical Persian football naming service for a professional Persian sports media network.\\n"
                    .
                    "Translate/transliterate ALL supplied football entity names into standard Persian sports-media spelling.\\n"
                    .
                    "Rules:\\n"
                    .
                    "1. Return ONLY valid JSON. No markdown, explanation, comments, or extra text.\\n"
                    .
                    "2. Return a JSON OBJECT keyed by the ORIGINAL input name exactly.\\n"
                    .
                    "3. Do not change, normalize, shorten, translate, or transliterate the JSON keys.\\n"
                    .
                    "4. Each JSON value must be ONLY the canonical Persian name for that exact key.\\n"
                    .
                    "5. Return every input name exactly once and do not add any extra key.\\n"
                    .
                    "6. Proper nouns should use established Persian football spelling or natural transliteration, not literal dictionary translation.\\n"
                    .
                    "7. Preserve suffixes/identity such as W, II, U21, FC, etc. when they distinguish the entity; render them naturally in Persian when appropriate.\\n"
                    .
                    "8. Example output:\\n"
                    .
                    "{\\\"Flamengo\\\":\\\"فلامنگو\\\",\\\"Real Madrid\\\":\\\"رئال مادرید\\\",\\\"Manchester City\\\":\\\"منچسترسیتی\\\"}\\n"
                    .
                    "Input JSON:\\n"
                    .
                    $text;

'''

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

if count != 1:
    print(f"ERROR: expected 1 translate_names_batch block, found {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: translate_names_batch -> exact source-name keyed JSON")
print("DONE ✅")
