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

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

needle = """            default:

                return
                    "Complete the following task accurately and return only the requested output:\\n\\n"
                    .
                    $text;
"""

replacement = r'''            case 'style_analysis':

                return
                    "Analyze the supplied Persian social-media text for WRITING STYLE only.\n"
                    .
                    "The goal is to learn current language habits for a dynamic football fan style engine.\n"
                    .
                    "Do NOT summarize the factual content.\n"
                    .
                    "Do NOT judge whether the factual claims are true.\n"
                    .
                    "Do NOT create a rewritten post.\n"
                    .
                    "Extract reusable STYLE PATTERNS rather than copying the entire sentence.\n\n"
                    .
                    "Possible pattern types include, but are not limited to:\n"
                    .
                    "- slang\n"
                    .
                    "- stretched_word\n"
                    .
                    "- reaction_style\n"
                    .
                    "- banter_style\n"
                    .
                    "- profanity_style\n"
                    .
                    "- humor_style\n"
                    .
                    "- emoji_pattern\n"
                    .
                    "- sentence_style\n"
                    .
                    "- punctuation_style\n"
                    .
                    "- opening_style\n"
                    .
                    "- closing_style\n"
                    .
                    "- emotional_style\n\n"
                    .
                    "Return ONLY valid JSON with this exact structure:\n"
                    .
                    "{\n"
                    .
                    "  \"language\":\"fa\",\n"
                    .
                    "  \"overall_style\":\"short description\",\n"
                    .
                    "  \"patterns\":[\n"
                    .
                    "    {\n"
                    .
                    "      \"pattern_type\":\"...\",\n"
                    .
                    "      \"pattern_text\":\"...\",\n"
                    .
                    "      \"strength\":0,\n"
                    .
                    "      \"confidence\":0\n"
                    .
                    "    }\n"
                    .
                    "  ]\n"
                    .
                    "}\n\n"
                    .
                    "Rules:\n"
                    .
                    "- strength and confidence must be integers from 0 to 100.\n"
                    .
                    "- Keep pattern_text short and reusable.\n"
                    .
                    "- Do not invent slang or patterns not visible in the input.\n"
                    .
                    "- Do not output markdown fences.\n\n"
                    .
                    "INPUT TEXT:\n"
                    .
                    $text;

            default:

                return
                    "Complete the following task accurately and return only the requested output:\n\n"
                    .
                    $text;
'''

if needle not in text:
    print("ERROR: default 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)
    print("ERROR: syntax check failed")
    sys.exit(1)

tmp.replace(target)

print("Patched: style_analysis task")
print("DONE ✅")
