#!/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 "EVENT PERSPECTIVE RULES V2" in text:
    print("Already patched.")
    sys.exit(0)

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

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

needle = """                $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
"""

replacement = """                $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.'
                    };

                /*
                |--------------------------------------------------------------------------
                | EVENT PERSPECTIVE RULES V2
                |--------------------------------------------------------------------------
                */

                $eventPerspectiveRule =
                    match ($eventType) {

                        'goal',
                        'penalty_goal',
                        'own_goal' =>
                            $perspective === 'own_team'
                                ? 'This is a scoring event for the fan team. Celebration is appropriate, but do not invent the quality or style of the goal.'
                                : 'The fan team conceded. React negatively or with concern, but do not invent defensive mistakes, tactical causes or blame unless explicitly supplied.',

                        'missed_penalty' =>
                            $perspective === 'own_team'
                                ? 'The fan team missed a penalty. Frustration or disbelief may be appropriate.'
                                : 'The opponent missed a penalty. Relief, celebration or teasing may be appropriate.',

                        'yellow_card' =>
                            $perspective === 'own_team'
                                ? 'A fan-team player received a yellow card. Reaction should be cautious, annoyed or concerned depending on personality.'
                                : 'An opponent player received a yellow card. Mild approval, teasing or tactical relief may be appropriate without inventing consequences.',

                        'red_card' =>
                            $perspective === 'own_team'
                                ? 'The fan team received a red card. Strong concern, anger or frustration may be appropriate.'
                                : 'The opponent received a red card. Celebration, relief or teasing may be appropriate, but do not claim the match is decided.',

                        'var_goal_cancelled' =>
                            $perspective === 'own_team'
                                ? 'A goal-related VAR decision went against the fan team. Frustration or disbelief may be appropriate.'
                                : 'A goal-related VAR decision went against the opponent. Relief or celebration may be appropriate.',

                        'var_penalty' =>
                            $perspective === 'own_team'
                                ? 'A VAR penalty event involves the fan team. React according to whether the supplied facts show it benefits or hurts the fan team.'
                                : 'A VAR penalty event involves the opponent. React from the fan-team perspective and do not assume the final decision beyond the supplied facts.',

                        'substitution' =>
                            'This is a substitution event. Keep the reaction lighter unless the supplied context makes the player or moment especially important.',

                        'match_start' =>
                            'The match has started. Use kickoff excitement from the fan-team perspective, without inventing tactics, lineup performance or match momentum.',

                        'halftime' =>
                            'It is halftime. React only to the supplied score/state. Do not invent first-half performance, chances, possession or tactical quality.',

                        'second_half' =>
                            'The second half has started. Keep it brief and fan-like. Do not invent tactical changes or substitutions unless supplied.',

                        'extra_time' =>
                            'The match has gone to extra time. Heightened tension is appropriate, but do not invent why extra time was reached.',

                        'penalties' =>
                            'The match has reached a penalty shootout. Strong tension is appropriate. Do not invent kick order or outcomes.',

                        'fulltime' =>
                            'The match is over. React from the fan-team perspective using only the supplied score/result. Celebrate a win, react negatively to a loss, and use a mixed/neutral fan reaction for a draw. Do not invent performance analysis.',

                        default =>
                            'React naturally from the fan-team perspective and stay strictly inside the supplied facts.'
                    };

                return
"""

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

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

needle2 = '''                    "PERSPECTIVE INSTRUCTION: {$perspectiveInstruction}\\n"
                    .
                    "EVENT TEAM: {$eventTeamName}\\n"
'''

replacement2 = '''                    "PERSPECTIVE INSTRUCTION: {$perspectiveInstruction}\\n"
                    .
                    "EVENT-SPECIFIC PERSPECTIVE RULE: {$eventPerspectiveRule}\\n"
                    .
                    "EVENT TEAM: {$eventTeamName}\\n"
'''

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

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

needle3 = '''                    "- 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"
'''

replacement3 = '''                    "- If perspective=opponent, the emotional direction should reflect the fan team's disappointment, concern, anger, sarcasm or criticism when appropriate.\\n"
                    .
                    "- Never invent defensive mistakes, bad marking, tactical failure, domination, pressure, missed chances, possession or match momentum unless those facts are explicitly supplied.\\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: fact discipline block not found")
    sys.exit(1)

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

text = text.replace(
    "<?php\n",
    "<?php\n/* EVENT PERSPECTIVE RULES V2 */\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("Event perspective rules V2 enabled ✅")
