#!/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_retry_fix_"
    + datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
)

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

# Fix visible version label everywhere.
text = text.replace(
    "STYLE ANALYZER V1.0",
    "STYLE ANALYZER V2.0"
)

marker = "INVALID AI JSON - RETRYING ONCE"

if marker not in text:

    old = """$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);
}
"""

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

/*
|--------------------------------------------------------------------------
| Retry once if provider returns truncated / malformed 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 "INVALID AI JSON AFTER RETRY" . PHP_EOL;
        echo "----------------------------------------------" . PHP_EOL;
        echo $raw . PHP_EOL;

        exit(1);
    }

    $result = $retryResult;
}
"""

    if old not in text:
        print("ERROR: JSON decode block not found")
        sys.exit(1)

    text = text.replace(old, new, 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("Retry + version label fixed ✅")
