<?php

declare(strict_types=1);

require_once __DIR__ . '/../../vendor/autoload.php';

use App\Framework\HttpClient\CurlHttpClient;
use App\Framework\Notification\Channels\Telegram\ChatIdDiscovery;
use App\Framework\Notification\Channels\Telegram\TelegramConfig;
use App\Framework\Notification\Channels\Telegram\ValueObjects\TelegramBotToken;

echo "🔍 Telegram Chat ID Discovery\n";
echo str_repeat('=', 60) . "\n\n";

try {
    // Replace with your bot token
    $botToken = TelegramBotToken::fromString('8185213800:AAG92qxtLbDbFQ3CSDOTAPH3H9UCuFS8mSc');

    echo "1️⃣ Creating Telegram configuration...\n";
    $config = new TelegramConfig(botToken: $botToken);
    echo "   ✅ Config created\n\n";

    echo "2️⃣ Creating Chat ID Discovery service...\n";
    $httpClient = new CurlHttpClient();
    $discovery = new ChatIdDiscovery($httpClient, $config);
    echo "   ✅ Discovery service created\n\n";

    echo "3️⃣ Fetching chat updates from Telegram...\n";
    echo "   ℹ️  Please make sure you've sent at least one message to your bot!\n\n";

    // Discover all chats
    $discovery->printDiscoveredChats();

    // Get most recent chat ID (usually yours)
    echo "🎯 Most Recent Chat ID:\n";
    echo str_repeat('=', 60) . "\n";
    $mostRecent = $discovery->getMostRecentChatId();

    if ($mostRecent) {
        echo "   📝 Use this Chat ID in your configuration:\n";
        echo "   💬 Chat ID: {$mostRecent->toString()}\n\n";
        echo "   📋 Copy this for TelegramConfig.php:\n";
        echo "   TelegramChatId::fromString('{$mostRecent->toString()}')\n\n";
    } else {
        echo "   ⚠️  No chat ID found.\n";
        echo "   📲 Please:\n";
        echo "      1. Open your bot: https://t.me/michael_schiemer_bot\n";
        echo "      2. Click 'START' or send any message\n";
        echo "      3. Run this script again\n\n";
    }

    echo "✅ Discovery completed!\n";
} catch (\Throwable $e) {
    echo "\n❌ Discovery failed: {$e->getMessage()}\n";
    echo "Stack trace:\n{$e->getTraceAsString()}\n";
    exit(1);
}
