#!/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 "FAN OUTPUT GUARD V1" in text:
    print("Already patched.")
    sys.exit(0)

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

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

needle = """    $text =
        sanitizeFanWriterOutput(
            (string)($result['text'] ?? '')
        );

    echo $text . PHP_EOL;
"""

replacement = """    $text =
        sanitizeFanWriterOutput(
            (string)($result['text'] ?? '')
        );

    /*
    |--------------------------------------------------------------------------
    | FAN OUTPUT GUARD V1
    |--------------------------------------------------------------------------
    |
    | Detects obvious unsupported narrative/context additions.
    | If detected, asks AI once for a fact-only rewrite.
    |--------------------------------------------------------------------------
    */

    $guardPatterns = [
        '/بالاخره/u',
        '/دوباره/u',
        '/قفل دروازه/u',
        '/کار(?:مون|مون|مان)? راحت/u',
        '/بازی دست ما/u',
        '/بازی مال ما/u',
        '/فاجعه(?:ست| بود)?/u',
        '/کاملاً مسلط/u',
        '/فشار آورد/u',
        '/دفاع(?:مون|مان)? افتضاح/u',
    ];

    $guardTriggered = false;

    foreach ($guardPatterns as $pattern) {
        if (preg_match($pattern, $text) === 1) {
            $guardTriggered = true;
            break;
        }
    }

    if ($guardTriggered) {

        $rewriteInput = $input;

        $rewriteInput['text'] =
            "Rewrite the candidate fan post using ONLY the supplied event facts.\\n"
            .
            "Remove unsupported history, previous-event assumptions, tactical analysis, momentum claims, score-history claims, or invented causes.\\n"
            .
            "Keep the same fan personality and emotional direction.\\n"
            .
            "Return only the corrected Persian post.\\n\\n"
            .
            "CANDIDATE POST:\\n"
            .
            $text
            .
            "\\n\\n"
            .
            "ORIGINAL EVENT FACTS:\\n"
            .
            implode("\\n", $eventTextParts);

        $rewriteResult =
            aiGateway(
                $pdo,
                'fan_commentary',
                $rewriteInput
            );

        if ($rewriteResult['ok'] ?? false) {

            $rewritten =
                sanitizeFanWriterOutput(
                    (string)($rewriteResult['text'] ?? '')
                );

            if ($rewritten !== '') {
                $text = $rewritten;
                echo "Output Guard:    REWRITTEN" . PHP_EOL;
            }

        } else {
            echo "Output Guard:    TRIGGERED / REWRITE FAILED" . PHP_EOL;
        }
    } else {
        echo "Output Guard:    PASS" . PHP_EOL;
    }

    echo $text . PHP_EOL;
"""

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

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

text = text.replace(
    "<?php\n",
    "<?php\n/* FAN OUTPUT GUARD 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 Output Guard V1 enabled ✅")
