#!/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("ERROR: ai_gateway.php not found")
    sys.exit(1)

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

backup = target.with_name(
    "ai_gateway.php.backup_fan_writer_v2_"
    + datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
)

shutil.copy2(target, backup)
print("Backup:", backup)

start = text.find("            case 'fan_commentary':")
end = text.find("            default:", start)

if start == -1 or end == -1:
    print("ERROR: fan prompt block not found")
    sys.exit(1)

replacement = r'''            case 'fan_commentary':
            case 'fan_banter':
            case 'news_rewrite':

                $persona =
                    trim(
                        (string)(
                            $input['persona']
                            ??
                            'Persian football fan'
                        )
                    );

                $subjectType =
                    trim(
                        (string)(
                            $input['subject_type']
                            ??
                            'team'
                        )
                    );

                $subjectName =
                    trim(
                        (string)(
                            $input['subject_name']
                            ??
                            ''
                        )
                    );

                $currentTeam =
                    trim(
                        (string)(
                            $input['current_team']
                            ??
                            ''
                        )
                    );

                $eventType =
                    trim(
                        (string)(
                            $input['event_type']
                            ??
                            $taskType
                        )
                    );

                $importance =
                    max(
                        0,
                        min(
                            100,
                            (int)(
                                $input['importance']
                                ??
                                50
                            )
                        )
                    );

                return
                    "You are the writing brain of a Persian football fan Telegram channel.\n"
                    .
                    "Your job is NOT to follow fixed templates. Decide naturally how a real fan with the supplied personality would react.\n\n"
                    .
                    "SUBJECT TYPE: {$subjectType}\n"
                    .
                    "SUBJECT: {$subjectName}\n"
                    .
                    "CURRENT TEAM CONTEXT: {$currentTeam}\n"
                    .
                    "EVENT TYPE: {$eventType}\n"
                    .
                    "EVENT IMPORTANCE: {$importance}/100\n"
                    .
                    "PERSONALITY: {$persona}\n\n"
                    .
                    "WRITING RULES:\n"
                    .
                    "- Write natural Persian for Telegram, not news-agency Persian and not AI-sounding prose.\n"
                    .
                    "- Adapt tone, length, excitement, humor, teasing, profanity, emojis and writing style to the personality and event importance.\n"
                    .
                    "- Do not use a fixed sentence pattern. Vary wording naturally between posts.\n"
                    .
                    "- Highly emotional football moments may naturally use Persian stretched writing or explosive fan reactions when appropriate. Do not force this on normal news.\n"
                    .
                    "- Quiet news, transfers, injuries or statements should naturally be calmer than goals, late winners, derby moments or rival defeats.\n"
                    .
                    "- If the subject is a player, use the player's current team only as context. Do not turn every player post into a team post.\n"
                    .
                    "- If the subject is a team, write from that team's fan perspective when the personality indicates strong team bias.\n"
                    .
                    "- Never invent scores, minutes, players, quotes, injuries, statistics, transfers, opponents or any other factual detail.\n"
                    .
                    "- Never imply match events not present in the supplied facts.\n"
                    .
                    "- Avoid generic filler and cliché motivational phrases unless they genuinely fit the personality.\n"
                    .
                    "- Avoid repetitive catchphrases across posts.\n"
                    .
                    "- Return ONLY the final Telegram-ready Persian text.\n\n"
                    .
                    "FACTS:\n"
                    .
                    $text
                    .
                    "\n";

'''

new_text = text[:start] + replacement + text[end:]

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

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

print(check.stdout.strip())

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

tmp.replace(target)

print("Patched Fan Writer V2 prompts successfully")
print("DONE ✅")
