#!/usr/bin/env python3
from pathlib import Path
import 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")
if "case 'translate_names_batch':" in text:
    print("translate_names_batch already exists")
    sys.exit(0)

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}")

anchor = "            case 'translate_text':"

block = '''            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 fences, explanation, comments, or extra text.\\n"
                    .
                    "2. Output MUST be a JSON array with exactly one object per input item.\\n"
                    .
                    "3. Preserve every input id exactly.\\n"
                    .
                    "4. Each object must contain exactly: id, persian_name.\\n"
                    .
                    "5. persian_name must contain only the best canonical Persian name for that exact entity.\\n"
                    .
                    "6. Do NOT literally translate proper nouns; use established Persian football spelling or natural transliteration.\\n"
                    .
                    "7. Do not invent entities or omit any input.\\n"
                    .
                    "8. Examples: Flamengo=>فلامنگو, Real Madrid=>رئال مادرید, Manchester City=>منچسترسیتی.\\n"
                    .
                    "Input JSON:\\n"
                    .
                    $text;

'''

if anchor not in text:
    print("ERROR: translate_text anchor not found")
    sys.exit(1)

text = text.replace(anchor, block + anchor, 1)

tmp = TARGET.with_suffix(".php.tmp")
tmp.write_text(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)
    sys.exit(1)

tmp.replace(TARGET)
print("Patched: translate_names_batch")
print("DONE ✅")
