#!/usr/bin/env python3

from pathlib import Path
import shutil
import datetime
import subprocess
import sys

target = Path("/home/pishvivy/social.pishibini.com/engine/fan_analyzer.php")

if not target.is_file():
    print("ERROR: fan_analyzer.php not found")
    sys.exit(1)

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

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

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


# ---------------------------------------------------------
# 1) Load team display name after team_api_id validation
# ---------------------------------------------------------

needle1 = """if ($teamApiId <= 0) {
    throw new RuntimeException(
        'Event has no valid team_api_id.'
    );
}
"""

replacement1 = """if ($teamApiId <= 0) {
    throw new RuntimeException(
        'Event has no valid team_api_id.'
    );
}


/*
|--------------------------------------------------------------------------
| Resolve Subject / Team Context
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
    SELECT
        name,
        persian_name
    FROM football_teams
    WHERE api_team_id = ?
    LIMIT 1
");

$stmt->execute([$teamApiId]);

$teamRow = $stmt->fetch(PDO::FETCH_ASSOC);

$currentTeamName =
    $teamRow
        ? trim(
            (string)(
                $teamRow['persian_name']
                ?: $teamRow['name']
            )
        )
        : ('Team #' . $teamApiId);


/*
|--------------------------------------------------------------------------
| Subject model
|--------------------------------------------------------------------------
|
| V2:
| - Team fan channels use subject_type=team.
|
| Future:
| - Player fan channels will use subject_type=player
| - current_team will still carry the player's team context.
|
*/

$subjectType = 'team';
$subjectName = $currentTeamName;
"""

if needle1 not in text:
    print("ERROR: team validation block not found")
    sys.exit(1)

text = text.replace(needle1, replacement1, 1)


# ---------------------------------------------------------
# 2) Replace AI input with structured Fan Writer V2 input
# ---------------------------------------------------------

needle2 = """    $input = [
        'text' => $eventText,
        'persona' => $persona,
        'target_language' => 'fa',
    ];
"""

replacement2 = """    $input = [
        'text' => $eventText,

        /*
        | Fan Writer V2 structured context
        */
        'persona' => $persona,
        'subject_type' => $subjectType,
        'subject_name' => $subjectName,
        'current_team' => $currentTeamName,
        'event_type' => (string)$event['event_type'],
        'importance' => (int)round(
            (float)$event['importance_score']
        ),

        'target_language' => 'fa',
    ];
"""

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

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


# ---------------------------------------------------------
# 3) Add structured context to preview output
# ---------------------------------------------------------

needle3 = """    echo "AI Task:        "
        . $task
        . PHP_EOL;

    echo "Persona:        "
"""

replacement3 = """    echo "AI Task:        "
        . $task
        . PHP_EOL;

    echo "Subject Type:   "
        . $subjectType
        . PHP_EOL;

    echo "Subject:        "
        . $subjectName
        . PHP_EOL;

    echo "Current Team:   "
        . $currentTeamName
        . PHP_EOL;

    echo "Importance:     "
        . (int)round((float)$event['importance_score'])
        . "/100"
        . PHP_EOL;

    echo "Persona:        "
"""

if needle3 not in text:
    print("ERROR: preview output block not found")
    sys.exit(1)

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


# ---------------------------------------------------------
# Syntax check
# ---------------------------------------------------------

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)
    print("ERROR: syntax check failed. Original file unchanged.")
    sys.exit(1)

tmp.replace(target)

print("Patched Fan Analyzer V2 successfully")
print("Structured context enabled:")
print(" - subject_type")
print(" - subject_name")
print(" - current_team")
print(" - event_type")
print(" - importance")
print("DONE ✅")
