#!/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")

if "FAN PERSPECTIVE WRITER V1" in text:
    print("Already patched.")
    sys.exit(0)

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

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

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

                return
"""

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

                /*
                |--------------------------------------------------------------------------
                | FAN PERSPECTIVE WRITER V1
                |--------------------------------------------------------------------------
                */

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

                $fanSide =
                    trim(
                        (string)(
                            $input['fan_side']
                            ??
                            ''
                        )
                    );

                $opponentTeam =
                    trim(
                        (string)(
                            $input['opponent_team']
                            ??
                            ''
                        )
                    );

                $fanGoals =
                    $input['fan_goals']
                    ??
                    null;

                $opponentGoals =
                    $input['opponent_goals']
                    ??
                    null;

                $eventTeamName =
                    trim(
                        (string)(
                            $input['event_team_name']
                            ??
                            ''
                        )
                    );

                $eventPlayerName =
                    trim(
                        (string)(
                            $input['event_player_name']
                            ??
                            ''
                        )
                    );

                $eventAssistName =
                    trim(
                        (string)(
                            $input['event_assist_name']
                            ??
                            ''
                        )
                    );

                $eventMinute =
                    $input['event_minute']
                    ??
                    null;

                $perspectiveInstruction =
                    match ($perspective) {

                        'own_team' =>
                            'The event happened FOR the fan team. React from the perspective of a supporter of the subject team. Positive excitement, celebration, relief or pride may be appropriate depending on the event.',

                        'opponent' =>
                            'The event happened FOR the opponent or AGAINST the fan team. React from the perspective of the fan team, not the opponent. Do not celebrate the opponent. Frustration, disbelief, criticism, worry, sarcasm or restrained reaction may be appropriate depending on personality and event.',

                        default =>
                            'Perspective is not fully known. Stay neutral enough to avoid reacting for the wrong team.'
                    };

                return
"""

if needle not in text:
    print("ERROR: importance block not found")
    sys.exit(1)

text = text.replace(needle, replacement, 1)

needle2 = '''                    "CURRENT TEAM CONTEXT: {$currentTeam}\\n"
                    .
                    "EVENT TYPE: {$eventType}\\n"
                    .
                    "EVENT IMPORTANCE: {$importance}/100\\n"
                    .
                    "PERSONALITY: {$persona}\\n"
'''

replacement2 = '''                    "CURRENT TEAM CONTEXT: {$currentTeam}\\n"
                    .
                    "OPPONENT: {$opponentTeam}\\n"
                    .
                    "FAN SIDE: {$fanSide}\\n"
                    .
                    "PERSPECTIVE: {$perspective}\\n"
                    .
                    "PERSPECTIVE INSTRUCTION: {$perspectiveInstruction}\\n"
                    .
                    "EVENT TEAM: {$eventTeamName}\\n"
                    .
                    "EVENT PLAYER: {$eventPlayerName}\\n"
                    .
                    "EVENT ASSIST: {$eventAssistName}\\n"
                    .
                    "EVENT MINUTE: "
                    . ($eventMinute !== null ? (string)$eventMinute : '-')
                    . "\\n"
                    .
                    "CURRENT SCORE FROM FAN VIEW: "
                    . ($fanGoals !== null && $opponentGoals !== null
                        ? ((string)$fanGoals . '-' . (string)$opponentGoals)
                        : '-')
                    . "\\n"
                    .
                    "EVENT TYPE: {$eventType}\\n"
                    .
                    "EVENT IMPORTANCE: {$importance}/100\\n"
                    .
                    "PERSONALITY: {$persona}\\n"
'''

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

text = text.replace(needle2, replacement2, 1)

needle3 = '''                    "- Adapt tone, length, excitement, humor, teasing, profanity, emojis and writing style to the personality and event importance.\\n"
                    .
'''

replacement3 = '''                    "- Adapt tone, length, excitement, humor, teasing, profanity, emojis and writing style to the personality and event importance.\\n"
                    .
                    "- Always write from the fan team's perspective. Never accidentally celebrate an opponent event.\\n"
                    .
                    "- If perspective=own_team, the emotional direction can be positive when appropriate.\\n"
                    .
                    "- If perspective=opponent, the emotional direction should reflect the fan team's disappointment, concern, anger, sarcasm or criticism when appropriate.\\n"
                    .
                    "- Do not invent score consequences, table consequences, match momentum or tactical meaning unless explicitly provided in the facts.\\n"
                    .
'''

if needle3 not in text:
    print("ERROR: writing rules marker not found")
    sys.exit(1)

text = text.replace(needle3, replacement3, 1)

text = text.replace(
    "<?php\n",
    "<?php\n/* FAN PERSPECTIVE WRITER V1 */\n",
    1
)

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

tmp.replace(target)

print("Fan perspective writer enabled ✅")
