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

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

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

if "function sanitizeFanWriterOutput" not in text:

    marker = """function fanBool(array $row, string $key, bool $default = true): bool
"""

    sanitizer = r'''function sanitizeFanWriterOutput(string $text): string
{
    $text = trim($text);

    /*
    |--------------------------------------------------------------------------
    | Remove accidental HTML/XML-like markup from model output.
    |--------------------------------------------------------------------------
    */

    $text =
        preg_replace(
            '/<\\/?[a-z][^>]*>/iu',
            '',
            $text
        )
        ?? $text;

    /*
    |--------------------------------------------------------------------------
    | Remove zero-width characters that sometimes arrive inside tags/text.
    |--------------------------------------------------------------------------
    */

    $text =
        preg_replace(
            '/[\\x{200B}-\\x{200D}\\x{FEFF}]/u',
            '',
            $text
        )
        ?? $text;

    /*
    |--------------------------------------------------------------------------
    | Clean excessive whitespace while preserving paragraph breaks.
    |--------------------------------------------------------------------------
    */

    $text =
        preg_replace(
            "/[ \\t]+\\n/u",
            "\\n",
            $text
        )
        ?? $text;

    $text =
        preg_replace(
            "/\\n{3,}/u",
            "\\n\\n",
            $text
        )
        ?? $text;

    return trim($text);
}


'''

    if marker not in text:
        print("ERROR: helper insertion marker not found")
        sys.exit(1)

    text = text.replace(
        marker,
        sanitizer + marker,
        1
    )

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

    echo $text . PHP_EOL;
"""

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

    echo $text . PHP_EOL;
"""

if needle not in text:
    print("ERROR: output 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 Writer output sanitizer enabled ✅")
