#!/usr/bin/env python3

from pathlib import Path
import sys

p = Path("/home/pishvivy/social.pishibini.com/engine/style_analyzer_v2.php")

if not p.is_file():
    print("ERROR: style_analyzer_v2.php not found")
    sys.exit(1)

s = p.read_text(encoding="utf-8")

if "STYLE_ANALYZER_V2_PATCHED" in s:
    print("Already patched. Nothing changed.")
    sys.exit(0)

s = s.replace(
    "STYLE ANALYZER V1.0",
    "STYLE ANALYZER V2.0",
    1
)

s = s.replace(
"""$mode = strtolower(trim((string)($argv[1] ?? 'preview')));

if ($mode !== 'preview') {
    throw new RuntimeException(
        'Style Analyzer V1 supports PREVIEW only.'
    );
}

$inputText = '';""",
"""$mode = strtolower(trim((string)($argv[1] ?? 'preview')));
$runMode = $mode === 'run';

if (!in_array($mode, ['preview', 'run'], true)) {
    throw new RuntimeException(
        'Mode must be preview or run.'
    );
}

$inputText = '';

$sourceId = null;
$sourcePostId = null;
$views = null;
$forwards = null;
$reactions = null;
$sourceAverageViews = null;

foreach ($argv as $arg) {

    if (str_starts_with($arg, '--source=')) {
        $sourceId = max(1, (int)substr($arg, 9));
    }

    if (str_starts_with($arg, '--post=')) {
        $sourcePostId = trim(substr($arg, 7));
    }

    if (str_starts_with($arg, '--views=')) {
        $views = max(0, (int)substr($arg, 8));
    }

    if (str_starts_with($arg, '--forwards=')) {
        $forwards = max(0, (int)substr($arg, 11));
    }

    if (str_starts_with($arg, '--reactions=')) {
        $reactions = max(0, (int)substr($arg, 12));
    }

    if (str_starts_with($arg, '--avg-views=')) {
        $sourceAverageViews = max(0, (int)substr($arg, 12));
    }
}""",
    1
)

s = s.replace(
    'echo "Mode:           PREVIEW" . PHP_EOL;',
    '''echo "Mode:           "
    . ($runMode ? "RUN" : "PREVIEW")
    . PHP_EOL;''',
    1
)

needle = '''echo PHP_EOL;
echo "AI" . PHP_EOL;'''

persistence = r'''
/*
|--------------------------------------------------------------------------
| Persistence
|--------------------------------------------------------------------------
*/

$savedPatterns = 0;
$savedObservations = 0;

if ($runMode) {

    if ($sourceId === null) {
        throw new RuntimeException('RUN mode requires --source.');
    }

    if ($sourcePostId === null || $sourcePostId === '') {
        throw new RuntimeException('RUN mode requires --post.');
    }

    $sourceStmt = $pdo->prepare("
        SELECT *
        FROM style_sources
        WHERE id = ?
          AND is_active = 1
        LIMIT 1
    ");

    $sourceStmt->execute([$sourceId]);

    $styleSource = $sourceStmt->fetch(PDO::FETCH_ASSOC);

    if (!$styleSource) {
        throw new RuntimeException(
            'Style source not found or inactive.'
        );
    }

    $performanceRatio = null;
    $performanceLift = null;
    $performanceScore = 0.0;

    if (
        $views !== null
        &&
        $sourceAverageViews !== null
        &&
        $sourceAverageViews > 0
    ) {
        $performanceRatio = $views / $sourceAverageViews;
        $performanceLift = $performanceRatio - 1.0;

        $cappedRatio =
            max(0.0, min(3.0, $performanceRatio));

        $performanceScore =
            round(($cappedRatio / 3.0) * 15.0, 2);
    }

    $pdo->beginTransaction();

    try {

        foreach ($patterns as $pattern) {

            if (!is_array($pattern)) {
                continue;
            }

            $type = trim((string)($pattern['pattern_type'] ?? ''));
            $patternText = trim((string)($pattern['pattern_text'] ?? ''));

            $aiConfidence =
                max(
                    0,
                    min(
                        100,
                        (int)($pattern['confidence'] ?? 0)
                    )
                );

            if (
                $type === ''
                ||
                $patternText === ''
                ||
                mb_strlen($patternText, 'UTF-8') > 500
            ) {
                continue;
            }

            $find = $pdo->prepare("
                SELECT *
                FROM style_patterns
                WHERE pattern_type = ?
                  AND pattern_text = ?
                  AND language = ?
                  AND audience_style <=> ?
                  AND subject_type <=> ?
                  AND subject_api_id <=> ?
                LIMIT 1
            ");

            $find->execute([
                $type,
                $patternText,
                (string)($styleSource['language'] ?? 'fa'),
                $styleSource['audience_style'] ?? null,
                $styleSource['subject_type'] ?? null,
                $styleSource['subject_api_id'] ?? null,
            ]);

            $existing = $find->fetch(PDO::FETCH_ASSOC);

            if ($existing) {

                $patternId = (int)$existing['id'];

            } else {

                $initialConfidence =
                    min(
                        40,
                        round($aiConfidence * 0.40, 2)
                    );

                $insertPattern = $pdo->prepare("
                    INSERT INTO style_patterns
                    (
                        pattern_type,
                        pattern_text,
                        language,
                        audience_style,
                        subject_type,
                        subject_api_id,
                        first_seen_at,
                        last_seen_at,
                        source_count,
                        usage_count,
                        freshness_score,
                        performance_score,
                        confidence_score,
                        avg_performance_lift,
                        status
                    )
                    VALUES
                    (
                        ?,?,?,?,?,?,
                        NOW(),
                        NOW(),
                        1,
                        0,
                        100,
                        ?,
                        ?,
                        ?,
                        'active'
                    )
                ");

                $insertPattern->execute([
                    $type,
                    $patternText,
                    (string)($styleSource['language'] ?? 'fa'),
                    $styleSource['audience_style'] ?? null,
                    $styleSource['subject_type'] ?? null,
                    $styleSource['subject_api_id'] ?? null,
                    $performanceScore,
                    $initialConfidence,
                    $performanceLift ?? 0
                ]);

                $patternId = (int)$pdo->lastInsertId();
                $savedPatterns++;
            }

            $obs = $pdo->prepare("
                INSERT IGNORE INTO style_observations
                (
                    style_source_id,
                    source_post_id,
                    pattern_id,
                    observed_text,
                    views,
                    forwards,
                    reactions,
                    source_average_views,
                    performance_ratio,
                    performance_lift,
                    observed_at
                )
                VALUES
                (
                    ?,?,?,?,?,?,?,?,?,?,NOW()
                )
            ");

            $obs->execute([
                $sourceId,
                $sourcePostId,
                $patternId,
                $inputText,
                $views,
                $forwards,
                $reactions,
                $sourceAverageViews,
                $performanceRatio,
                $performanceLift
            ]);

            if ($obs->rowCount() > 0) {

                $savedObservations++;

                $stats = $pdo->prepare("
                    SELECT
                        COUNT(*) AS usage_count,
                        COUNT(DISTINCT style_source_id) AS source_count,
                        AVG(COALESCE(performance_lift,0)) AS avg_lift
                    FROM style_observations
                    WHERE pattern_id = ?
                ");

                $stats->execute([$patternId]);
                $agg = $stats->fetch(PDO::FETCH_ASSOC);

                $usageCount = (int)($agg['usage_count'] ?? 0);
                $sourceCount = (int)($agg['source_count'] ?? 0);
                $avgLift = (float)($agg['avg_lift'] ?? 0);

                $update = $pdo->prepare("
                    UPDATE style_patterns
                    SET
                        last_seen_at = NOW(),
                        usage_count = ?,
                        source_count = ?,
                        avg_performance_lift = ?,
                        performance_score = ?,
                        confidence_score =
                            LEAST(
                                100,
                                ?
                                +
                                LEAST(35, ? * 10)
                                +
                                LEAST(15, ? * 2)
                            )
                    WHERE id = ?
                ");

                $baseConfidence =
                    min(40, round($aiConfidence * 0.40, 2));

                $update->execute([
                    $usageCount,
                    $sourceCount,
                    $avgLift,
                    $performanceScore,
                    $baseConfidence,
                    $sourceCount,
                    $usageCount,
                    $patternId
                ]);
            }
        }

        $pdo->commit();

    } catch (Throwable $e) {

        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }

        throw $e;
    }

    echo PHP_EOL;
    echo "DATABASE" . PHP_EOL;
    echo "----------------------------------------------" . PHP_EOL;
    echo "New Patterns:   " . $savedPatterns . PHP_EOL;
    echo "Observations:   " . $savedObservations . PHP_EOL;
    echo "Performance:    "
        . number_format($performanceScore, 2)
        . "/15"
        . PHP_EOL;
}

'''

if needle not in s:
    print("ERROR: AI marker not found")
    sys.exit(1)

s = s.replace(
    needle,
    persistence + "\n" + needle,
    1
)

s = s.replace(
    'echo "STYLE ANALYSIS COMPLETE ✅" . PHP_EOL;',
    'echo "STYLE ANALYSIS V2 COMPLETE ✅" . PHP_EOL;',
    1
)

s = s.replace(
    'echo "Preview only - nothing was saved." . PHP_EOL;',
    '''echo (
    $runMode
        ? "Learning data saved."
        : "Preview only - nothing was saved."
) . PHP_EOL;''',
    1
)

s = s.replace(
    "<?php\n",
    "<?php\n// STYLE_ANALYZER_V2_PATCHED\n",
    1
)

p.write_text(s, encoding="utf-8")

print("V2 patch applied once ✅")
