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

if "STYLE MEMORY CONTEXT" in text:
    print("Already patched.")
    sys.exit(0)

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

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

needle = """    $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',
    ];
"""

replacement = """    /*
    |--------------------------------------------------------------------------
    | STYLE MEMORY CONTEXT
    |--------------------------------------------------------------------------
    */

    $styleMemory = '';

    $memoryCommand =
        'php '
        . escapeshellarg(__DIR__ . '/style_memory_builder.php')
        . ' json'
        . ' --audience='
        . escapeshellarg((string)$row['personality_slug'])
        . ' --subject-type='
        . escapeshellarg($subjectType)
        . ' --subject-id='
        . escapeshellarg((string)$teamApiId);

    $memoryOutput = [];
    $memoryExitCode = 1;

    exec(
        $memoryCommand . ' 2>&1',
        $memoryOutput,
        $memoryExitCode
    );

    if ($memoryExitCode === 0) {

        $memoryJson =
            json_decode(
                implode(PHP_EOL, $memoryOutput),
                true
            );

        if (is_array($memoryJson)) {
            $styleMemory =
                trim(
                    (string)(
                        $memoryJson['memory_text']
                        ??
                        ''
                    )
                );
        }
    }

    echo "Style Memory:   "
        . ($styleMemory !== '' ? 'LOADED' : 'EMPTY')
        . PHP_EOL;

    $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']
        ),

        'style_memory' => $styleMemory,

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

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

text = text.replace(needle, replacement, 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 Analyzer style memory enabled ✅")
