<?php

declare(strict_types=1);

if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    echo "This script can be run only from CLI.\n";
    exit(1);
}

require_once __DIR__ . '/../src/config.php';
require_once __DIR__ . '/../src/storage.php';
require_once __DIR__ . '/../src/history.php';

$history = listChatHistories();
$migrated = [];
$skipped = 0;

foreach ((array) ($history['chats'] ?? []) as $chatKey => $chat) {
    if (!is_array($chat)) {
        $skipped++;
        continue;
    }

    $context = (array) ($chat['context'] ?? []);
    $isOpenLine = trim((string) ($context['open_line_id'] ?? '')) !== '';
    $hasFollowupState = trim((string) ($chat['followup_started_at'] ?? '')) !== ''
        || (array) ($chat['followups'] ?? []) !== []
        || trim((string) ($chat['followups_stopped_at'] ?? '')) !== ''
        || trim((string) ($chat['no_response_marked_at'] ?? '')) !== '';

    if (!$isOpenLine && !$hasFollowupState) {
        $skipped++;
        continue;
    }

    saveChatFollowupOperationalState((string) $chatKey, $chat);
    $migrated[] = (string) $chatKey;
}

echo json_encode([
    'ok' => true,
    'migrated_count' => count($migrated),
    'skipped_count' => $skipped,
    'migrated' => $migrated,
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . PHP_EOL;

