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

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

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

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

needle = """                $eventType =
                    trim(
                        (string)(
                            $input['event_type']
                            ??
                            $taskType
                        )
                    );
"""

replacement = """                $eventType =
                    trim(
                        (string)(
                            $input['event_type']
                            ??
                            $taskType
                        )
                    );

                $styleMemory =
                    trim(
                        (string)(
                            $input['style_memory']
                            ??
                            ''
                        )
                    );
"""

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

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

needle2 = '''                    "PERSONALITY: {$persona}\\n\\n"
                    .
                    "WRITING RULES:\\n"
'''

replacement2 = '''                    "PERSONALITY: {$persona}\\n"
                    .
                    "LEARNED STYLE MEMORY:\\n"
                    .
                    ($styleMemory !== ''
                        ? $styleMemory
                        : 'No learned style memory available.')
                    .
                    "\\n\\n"
                    .
                    "WRITING RULES:\\n"
'''

if needle2 not in text:
    print("ERROR: prompt personality block not found")
    sys.exit(1)

text = text.replace(needle2, replacement2, 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("AI Gateway style memory support enabled ✅")
