#!/usr/bin/env python3
from pathlib import Path
import shutil
import datetime
import subprocess
import sys

TARGET = Path("/home/pishvivy/social.pishibini.com/engine/ai_gateway.php")

if not TARGET.is_file():
    print(f"ERROR: not found: {TARGET}")
    sys.exit(1)

text = TARGET.read_text(encoding="utf-8")
original = text

backup = TARGET.with_name(
    "ai_gateway.php.backup_"
    + datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
)
shutil.copy2(TARGET, backup)
print(f"Backup: {backup}")

old_backoff = '''                usleep(
                    $attempt === 1
                        ? 400000
                        : 900000
                );'''

new_backoff = '''                usleep(
                    $attempt === 1
                        ? 1000000
                        : 2500000
                );'''

if old_backoff in text:
    text = text.replace(old_backoff, new_backoff, 1)
    print("Patched: retry backoff")
else:
    print("WARN: retry backoff anchor not found")

old_temp = '''                'temporary' =>
                    aiGatewayTemporaryHttpCode(
                        (int)$http['http_code']
                    ),'''

new_temp = '''                'temporary' =>
                    aiGatewayTemporaryFailure(
                        (int)$http['http_code'],
                        $error
                    ),'''

count = text.count(old_temp)

if count > 0:
    text = text.replace(old_temp, new_temp)
    print(f"Patched: temporary detection in {count} adapter(s)")
else:
    print("WARN: provider temporary anchors not found")

if "function aiGatewayTemporaryFailure(" not in text:
    anchor = '''    function aiGatewayCleanOutput(
        string $text,
        string $taskType
    ): string {'''

    helper = '''    function aiGatewayTemporaryFailure(
        int $httpCode,
        string $error
    ): bool {

        if (
            aiGatewayTemporaryHttpCode(
                $httpCode
            )
        ) {
            return true;
        }

        if ($httpCode !== 0) {
            return false;
        }

        $errorLower =
            strtolower(
                trim(
                    $error
                )
            );

        if ($errorLower === '') {
            return true;
        }

        $temporaryNeedles = [
            'timed out',
            'timeout',
            'could not resolve host',
            'failed to connect',
            'connection reset',
            'connection refused',
            'connection aborted',
            'temporary failure',
            'network is unreachable',
            'empty reply from server',
            'recv failure',
            'send failure',
            'ssl connection timeout',
        ];

        foreach ($temporaryNeedles as $needle) {

            if (
                str_contains(
                    $errorLower,
                    $needle
                )
            ) {
                return true;
            }
        }

        return false;
    }


'''

    if anchor not in text:
        print("ERROR: clean-output anchor not found")
        sys.exit(1)

    text = text.replace(anchor, helper + anchor, 1)
    print("Patched: temporary network failure helper")
else:
    print("Temporary failure helper already exists")

if text == original:
    print("No changes were necessary.")
    sys.exit(0)

tmp = TARGET.with_suffix(".php.tmp")
tmp.write_text(text, encoding="utf-8")

check = subprocess.run(
    ["php", "-l", str(tmp)],
    text=True,
    capture_output=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 left unchanged.")
    sys.exit(1)

tmp.replace(TARGET)

print("ai_gateway.php patched successfully")
print("Retryable: HTTP 408/425/429/5xx + cURL timeout/network failures")
print("Fallback: next active provider after retries")
print("DONE ✅")
