#!/usr/bin/env python3
from pathlib import Path
import shutil
import datetime
import subprocess
import 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}")

old = '''                return
                    "You are the centralized Persian naming service for a football media network.\\n"
                    .
                    "Convert the following {$entityType} name to the standard, natural Persian name used by Persian football media.\\n"
                    .
                    "Rules:\\n"
                    .
                    "- Return ONLY the Persian name.\\n"
                    .
                    "- No explanation, quotes, markdown, punctuation around the answer, or alternatives.\\n"
                    .
                    "- Prefer the established Persian football spelling when one exists.\\n"
                    .
                    "- For proper names, transliterate naturally; do not translate the literal meaning unless Persian media normally does so.\\n"
                    .
                    "- Preserve club identity and avoid inventing abbreviations.\\n"
                    .
                    "Name: {$text}";'''

new = '''                $context =
                    trim(
                        (string)(
                            $input['context']
                            ??
                            ''
                        )
                    );

                $contextLine =
                    $context !== ''
                        ? "\\nContext: {$context}"
                        : '';

                return
                    "You are the canonical Persian football naming service for a professional Persian sports media network.\\n"
                    .
                    "Your job is NOT literal translation. Your job is to return the standard Persian spelling/transliteration used by Persian football media for the exact football entity.\\n"
                    .
                    "Entity type: {$entityType}\\n"
                    .
                    "Rules:\\n"
                    .
                    "1. Return ONLY one Persian name. No explanation, alternatives, quotes, markdown, parentheses, or Latin text.\\n"
                    .
                    "2. Prefer the established spelling used by Persian football media when known.\\n"
                    .
                    "3. For club, player, stadium, city, league, or competition proper names, transliterate the proper noun naturally based on its real-language pronunciation; do NOT translate its dictionary meaning.\\n"
                    .
                    "4. Do not confuse a football proper noun with a similarly spelled English common word.\\n"
                    .
                    "5. Preserve particles and compound-name identity such as del, de, da, do, van, von, al, el, etc.\\n"
                    .
                    "6. Do not add words or abbreviations that are not present in the supplied name.\\n"
                    .
                    "7. If a well-known Persian sports spelling exists, use that conventional spelling even if another phonetic spelling is possible.\\n"
                    .
                    "Canonical examples:\\n"
                    .
                    "Flamengo => فلامنگو\\n"
                    .
                    "Manchester City => منچسترسیتی\\n"
                    .
                    "Real Madrid => رئال مادرید\\n"
                    .
                    "Independiente del Valle => ایندپندینته دل‌وایه\\n"
                    .
                    "Cienciano => سینسیانو\\n"
                    .
                    "Atletico Torque => اتلتیکو تورکه\\n"
                    .
                    "Boca Juniors => بوکا جونیورز\\n"
                    .
                    "Paris Saint-Germain => پاری سن ژرمن\\n"
                    .
                    "Now return the canonical Persian name for this exact entity."
                    .
                    $contextLine
                    .
                    "\\nName: {$text}";'''

if old not in text:
    print("ERROR: translate_name prompt block not found")
    sys.exit(1)

patched = text.replace(old, new, 1)

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

tmp.replace(TARGET)

print("Patched: translate_name prompt V2")
print("ai_gateway.php updated successfully")
print("DONE ✅")
