#!/usr/bin/env python3

from pathlib import Path
import shutil
import datetime
import subprocess
import sys

target = Path("/home/pishvivy/social.pishibini.com/engine/style_memory_builder.php")

if not target.is_file():
    print("ERROR: style_memory_builder.php not found")
    sys.exit(1)

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

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

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

if "function abstractStyleSignal" not in text:

    marker = """/*
|--------------------------------------------------------------------------
| Load candidate patterns
|--------------------------------------------------------------------------
"""

    helper = r'''
function abstractStyleSignal(
    string $type,
    string $pattern
): string {

    $type = strtolower(trim($type));
    $pattern = trim($pattern);

    switch ($type) {

        case 'stretched_word':
            return
                'Stretched Persian words are currently common in high-emotion football reactions. '
                .
                'Use stretched writing only when the moment genuinely feels intense, and create fresh wording instead of copying observed words.';

        case 'reaction_style':
            return
                'Short, immediate shock/excitement reactions are currently common. '
                .
                'React directly to the event instead of writing formal commentary or long explanations.';

        case 'emoji_pattern':
            return
                'Compact emotional emoji combinations are currently common in football reactions. '
                .
                'Use a small number of context-appropriate emojis and vary them naturally instead of copying observed emoji pairs.';

        case 'sentence_style':
            return
                'Casual Telegram-style sentences are currently short, conversational and often avoid formal sentence endings.';

        case 'slang':
            return
                'Current Persian football slang is used in very informal reactions. '
                .
                'Use contemporary slang only when it fits naturally; do not repeat observed slang mechanically.';

        case 'banter_style':
            return
                'Current football banter is short, direct and conversational rather than formal or scripted.';

        case 'profanity_style':
            return
                'Very informal football reactions may contain mild-to-strong profanity depending on channel personality. '
                .
                'Match the configured profanity level and avoid forcing profanity into every post.';

        case 'humor_style':
            return
                'Current fan humor tends to be brief, reactive and conversational rather than setup-heavy or joke-like.';

        case 'punctuation_style':
            return
                'Informal football reactions currently use expressive punctuation sparingly and often rely more on wording and emotion than formal punctuation.';

        case 'opening_style':
            return
                'Current fan posts often begin immediately with the emotional reaction instead of a formal introduction.';

        case 'closing_style':
            return
                'Current fan posts often end quickly after the core reaction rather than adding a formal conclusion.';

        case 'emotional_style':
            return
                'Match emotional intensity closely to the importance of the event, with stronger reactions reserved for genuinely bigger moments.';

        default:
            return
                'A current informal Persian football writing pattern was observed. '
                .
                'Use it only as a general style signal and create fresh wording.';
    }
}


'''

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

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

old = """    $memoryLines[] = [
        'type' => $type,
        'pattern' => $text,
        'confidence' => number_format($confidence, 2, '.', ''),
        'freshness' => number_format($freshness, 2, '.', ''),
        'sources' => $sourceCount,
        'usage' => $usageCount,
    ];
"""

new = """    $memoryLines[] = [
        'type' => $type,

        /*
        | Raw pattern stays available for admin/debug/scoring,
        | but is NOT used directly in writer memory.
        */
        'pattern' => $text,

        'signal' =>
            abstractStyleSignal(
                $type,
                $text
            ),

        'confidence' => number_format($confidence, 2, '.', ''),
        'freshness' => number_format($freshness, 2, '.', ''),
        'sources' => $sourceCount,
        'usage' => $usageCount,
    ];
"""

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

text = text.replace(old, new, 1)

old2 = """    foreach ($memoryLines as $item) {

        $parts[] =
            '- '
            .
            $item['type']
            .
            ': '
            .
            $item['pattern'];
    }
"""

new2 = """    /*
    |--------------------------------------------------------------------------
    | De-duplicate abstract signals
    |--------------------------------------------------------------------------
    */

    $seenSignals = [];

    foreach ($memoryLines as $item) {

        $signal =
            trim(
                (string)(
                    $item['signal']
                    ??
                    ''
                )
            );

        if ($signal === '') {
            continue;
        }

        $signalKey =
            mb_strtolower(
                $signal,
                'UTF-8'
            );

        if (isset($seenSignals[$signalKey])) {
            continue;
        }

        $seenSignals[$signalKey] = true;

        $parts[] =
            '- '
            .
            $signal;
    }
"""

if old2 not in text:
    print("ERROR: summary pattern block not found")
    sys.exit(1)

text = text.replace(old2, new2, 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("Abstract Style Memory enabled ✅")
