#!/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("ERROR: ai_gateway.php not found")
    sys.exit(1)

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

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

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

needle = '''                    "LEARNED STYLE MEMORY:\\n"
                    .
                    ($styleMemory !== ''
                        ? $styleMemory
                        : 'No learned style memory available.')
                    .
                    "\\n\\n"
                    .
                    "WRITING RULES:\\n"
'''

replacement = '''                    "LEARNED STYLE MEMORY:\\n"
                    .
                    ($styleMemory !== ''
                        ? $styleMemory
                        : 'No learned style memory available.')
                    .
                    "\\n\\n"
                    .
                    "STYLE MEMORY RULES:\\n"
                    .
                    "- Treat learned style memory as soft guidance, not as a phrase bank.\\n"
                    .
                    "- Do not mechanically copy learned phrases, slang, emoji combinations, or sentence patterns.\\n"
                    .
                    "- Generalize the style signal and produce fresh wording that fits the current event.\\n"
                    .
                    "- Reusing a learned phrase is allowed only when it sounds natural and not repetitive.\\n"
                    .
                    "- Do not force slang or stretched words into every emotional post.\\n\\n"
                    .
                    "WRITING RULES:\\n"
'''

if needle not in text:
    print("ERROR: learned style memory prompt 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("Soft style memory rules enabled ✅")
