#!/usr/bin/env python3

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

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

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

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

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

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

# ---------------------------------------------------------
# 1) Allow preview + draft
# ---------------------------------------------------------

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

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

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

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

$draftMode = $mode === 'draft';
"""

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

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


# ---------------------------------------------------------
# 2) Header mode
# ---------------------------------------------------------

text = text.replace(
    'echo "Mode:           PREVIEW" . PHP_EOL;',
    '''echo "Mode:           "
    . ($draftMode ? "DRAFT" : "PREVIEW")
    . PHP_EOL;''',
    1
)


# ---------------------------------------------------------
# 3) Insert draft persistence after sanitized AI text
# ---------------------------------------------------------

needle = """    echo $text . PHP_EOL;

    echo PHP_EOL;
    echo "Provider:       "
"""

replacement = """    echo $text . PHP_EOL;

    /*
    |--------------------------------------------------------------------------
    | Draft persistence
    |--------------------------------------------------------------------------
    |
    | Safety:
    | - posts.status = draft
    | - publish_queue.status = hold
    | - NOTHING gets status queued
    | - NOTHING is sent to publisher_queue
    |--------------------------------------------------------------------------
    */

    if ($draftMode) {

        $channelId = (int)$row['id'];

        $dedupeHash =
            hash(
                'sha256',
                'fan_event:'
                . $eventId
                . ':channel:'
                . $channelId
            );

        $findPost = $pdo->prepare("
            SELECT id
            FROM posts
            WHERE dedupe_hash = ?
            LIMIT 1
        ");

        $findPost->execute([$dedupeHash]);

        $existingPostId =
            $findPost->fetchColumn();

        if ($existingPostId) {

            $postId = (int)$existingPostId;

            $updatePost = $pdo->prepare("
                UPDATE posts
                SET
                    text_content = ?,
                    score = ?,
                    status = 'draft',
                    updated_at = CURRENT_TIMESTAMP
                WHERE id = ?
            ");

            $updatePost->execute([
                $text,
                (float)$event['importance_score'],
                $postId
            ]);

            echo "Draft Post:     UPDATED #"
                . $postId
                . PHP_EOL;

        } else {

            $insertPost = $pdo->prepare("
                INSERT INTO posts
                (
                    source_id,
                    source_message_id,
                    source_published_at,
                    content_type,
                    text_content,
                    media_type,
                    media_file_id,
                    source_views,
                    source_forwards,
                    score,
                    dedupe_hash,
                    status,
                    collected_at
                )
                VALUES
                (
                    NULL,
                    NULL,
                    ?,
                    'text',
                    ?,
                    NULL,
                    NULL,
                    NULL,
                    NULL,
                    ?,
                    ?,
                    'draft',
                    CURRENT_TIMESTAMP
                )
            ");

            $insertPost->execute([
                $event['event_at'] ?: null,
                $text,
                (float)$event['importance_score'],
                $dedupeHash
            ]);

            $postId =
                (int)$pdo->lastInsertId();

            echo "Draft Post:     CREATED #"
                . $postId
                . PHP_EOL;
        }

        /*
        |--------------------------------------------------------------------------
        | Queue as HOLD only
        |--------------------------------------------------------------------------
        */

        $findQueue = $pdo->prepare("
            SELECT id
            FROM publish_queue
            WHERE channel_id = ?
              AND post_id = ?
            LIMIT 1
        ");

        $findQueue->execute([
            $channelId,
            $postId
        ]);

        $existingQueueId =
            $findQueue->fetchColumn();

        if ($existingQueueId) {

            $queueId =
                (int)$existingQueueId;

            $updateQueue = $pdo->prepare("
                UPDATE publish_queue
                SET
                    status = 'hold',
                    priority = ?,
                    scheduled_at = NULL,
                    last_error = NULL,
                    updated_at = CURRENT_TIMESTAMP
                WHERE id = ?
            ");

            $updateQueue->execute([
                max(
                    1,
                    100 - (int)round(
                        (float)$event['importance_score']
                    )
                ),
                $queueId
            ]);

            echo "Publish Queue:  HOLD UPDATED #"
                . $queueId
                . PHP_EOL;

        } else {

            $insertQueue = $pdo->prepare("
                INSERT INTO publish_queue
                (
                    channel_id,
                    post_id,
                    priority,
                    scheduled_at,
                    status,
                    attempts
                )
                VALUES
                (
                    ?,?,?,NULL,'hold',0
                )
            ");

            $insertQueue->execute([
                $channelId,
                $postId,
                max(
                    1,
                    100 - (int)round(
                        (float)$event['importance_score']
                    )
                )
            ]);

            $queueId =
                (int)$pdo->lastInsertId();

            echo "Publish Queue:  HOLD CREATED #"
                . $queueId
                . PHP_EOL;
        }

        echo "Telegram:       NOT PUBLISHED" . PHP_EOL;
    }

    echo PHP_EOL;
    echo "Provider:       "
"""

if needle not in text:
    print("ERROR: AI output insertion point not found")
    sys.exit(1)

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


# ---------------------------------------------------------
# 4) Footer
# ---------------------------------------------------------

old_footer = """echo "FAN ANALYZER COMPLETE ✅" . PHP_EOL;
echo "Nothing was queued or published." . PHP_EOL;
"""

new_footer = """echo "FAN ANALYZER COMPLETE ✅" . PHP_EOL;

if ($draftMode) {
    echo "Draft saved. Queue status is HOLD." . PHP_EOL;
    echo "Nothing was published to Telegram." . PHP_EOL;
} else {
    echo "Nothing was queued or published." . PHP_EOL;
}
"""

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

text = text.replace(old_footer, new_footer, 1)


# ---------------------------------------------------------
# Syntax check
# ---------------------------------------------------------

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("Fan Analyzer draft mode enabled ✅")
