#!/usr/bin/env python3

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

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

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

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

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

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

needle = """$decoded =
    json_decode(
        $raw,
        true
    );

if (!is_array($decoded)) {

    echo PHP_EOL;
    echo "INVALID AI JSON" . PHP_EOL;
    echo "----------------------------------------------" . PHP_EOL;
    echo $raw . PHP_EOL;

    exit(1);
}
"""

replacement = """$decoded =
    json_decode(
        $raw,
        true
    );

/*
|--------------------------------------------------------------------------
| Retry once on malformed / truncated JSON
|--------------------------------------------------------------------------
*/

if (!is_array($decoded)) {

    echo PHP_EOL;
    echo "INVALID AI JSON - RETRYING ONCE" . PHP_EOL;
    echo "----------------------------------------------" . PHP_EOL;

    $retryResult =
        aiGateway(
            $pdo,
            'style_analysis',
            [
                'text' => $inputText,
                'target_language' => 'fa',
            ],
            [
                'attempts_per_provider' => 2,
            ]
        );

    if (!($retryResult['ok'] ?? false)) {

        echo "AI RETRY ERROR" . PHP_EOL;
        echo ($retryResult['error'] ?? 'Unknown retry error')
            . PHP_EOL;

        exit(1);
    }

    $raw =
        stripStyleJsonFences(
            (string)($retryResult['text'] ?? '')
        );

    $decoded =
        json_decode(
            $raw,
            true
        );

    if (!is_array($decoded)) {

        echo PHP_EOL;
        echo "INVALID AI JSON AFTER RETRY" . PHP_EOL;
        echo "----------------------------------------------" . PHP_EOL;
        echo $raw . PHP_EOL;

        exit(1);
    }

    /*
    | Use retry provider/model in the final report.
    */
    $result = $retryResult;
}
"""

if needle not in text:
    print("ERROR: JSON decode 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("Patched JSON retry successfully")
print("DONE ✅")
