<?php
declare(strict_types=1);

const BOT_TOKEN = '8909102622:AAEl0AYN-dLGeYX_-en8udMMKh2CnZP_beo';
const BOT_USERNAME = 'TahaAi_Robot';
const AI_API_URL = 'https://api.bluesminds.com/v1/chat/completions';
const AI_API_KEY = 'sk-TRqTZX5ndLIuPOogiGFmOh4LvQecDwggxfN98ADLfX9NA0WC';
const DEFAULT_MODEL = 'gpt-4o';
const TEMPERATURE = 0.7;
const DATA_DIR = __DIR__ . '/taha_data';
const LOCK_FILE = DATA_DIR . '/ai.lock';
const AVAILABLE_MODELS = ['gpt-4o', 'gpt-5-mini', 'gpt-5.2-chat', 'gpt-5.3-codex', 'gpt-5.5', 'gpt-5.6-luna'];

if (!is_dir(DATA_DIR)) {
    mkdir(DATA_DIR, 0755, true);
}

function tgRequest(string $method, array $params = []): ?array {
    $ch = curl_init('https://api.telegram.org/bot' . BOT_TOKEN . '/' . $method);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($params),
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_TIMEOUT => 60,
        CURLOPT_CONNECTTIMEOUT => 10,
    ]);
    $res = curl_exec($ch);
    curl_close($ch);
    return $res ? json_decode($res, true) : null;
}

function sendMessage(int|string $chatId, string $text, array $extra = []): ?array {
    return tgRequest('sendMessage', array_merge([
        'chat_id' => $chatId,
        'text' => $text,
        'parse_mode' => 'HTML',
    ], $extra));
}

function editMessage(int|string $chatId, int $messageId, string $text, array $extra = []): ?array {
    return tgRequest('editMessageText', array_merge([
        'chat_id' => $chatId,
        'message_id' => $messageId,
        'text' => $text,
        'parse_mode' => 'HTML',
    ], $extra));
}

function answerCallback(string $callbackId, string $text = ''): void {
    tgRequest('answerCallbackQuery', [
        'callback_query_id' => $callbackId,
        'text' => $text,
        'show_alert' => false,
    ]);
}

function userFile(int|string $chatId): string {
    return DATA_DIR . '/u_' . preg_replace('/[^0-9\-]/', '', (string)$chatId) . '.json';
}

function loadUser(int|string $chatId): array {
    $file = userFile($chatId);
    if (!is_file($file)) {
        return [
            'model' => DEFAULT_MODEL,
            'messages' => [],
            'title' => 'گفتگوی جدید',
        ];
    }
    $data = json_decode(file_get_contents($file), true);
    return is_array($data) ? $data : [
        'model' => DEFAULT_MODEL,
        'messages' => [],
        'title' => 'گفتگوی جدید',
    ];
}

function saveUser(int|string $chatId, array $data): void {
    file_put_contents(userFile($chatId), json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT), LOCK_EX);
}

function resetChat(int|string $chatId): void {
    $data = loadUser($chatId);
    $data['messages'] = [];
    $data['title'] = 'گفتگوی جدید';
    saveUser($chatId, $data);
}

function mainMenuKeyboard(): array {
    return [
        'inline_keyboard' => [
            [
                ['text' => '💬 گفتگوی جدید', 'callback_data' => 'newchat'],
                ['text' => '🧠 انتخاب مدل', 'callback_data' => 'models'],
            ],
            [
                ['text' => '📊 وضعیت', 'callback_data' => 'status'],
                ['text' => '🗑 پاک‌سازی حافظه', 'callback_data' => 'clear'],
            ],
            [
                ['text' => 'ℹ️ راهنما', 'callback_data' => 'help'],
            ],
        ],
    ];
}

function modelsKeyboard(string $current): array {
    $rows = [];
    $row = [];
    foreach (AVAILABLE_MODELS as $m) {
        $label = ($m === $current ? '✅ ' : '') . $m;
        $row[] = ['text' => $label, 'callback_data' => 'setmodel_' . $m];
        if (count($row) === 2) {
            $rows[] = $row;
            $row = [];
        }
    }
    if ($row) {
        $rows[] = $row;
    }
    $rows[] = [['text' => '🔙 بازگشت', 'callback_data' => 'menu']];
    return ['inline_keyboard' => $rows];
}

function groupClearKeyboard(): array {
    return [
        'inline_keyboard' => [
            [
                ['text' => '🗑 پاک‌سازی حافظه گروه', 'callback_data' => 'clear'],
            ],
        ],
    ];
}

function callAI(array $messages, string $model): string {
    $lock = fopen(LOCK_FILE, 'c+');
    if (!$lock) {
        return 'خطا در سیستم قفل. لطفاً دوباره تلاش کنید.';
    }

    $acquired = false;
    $tries = 0;
    while ($tries < 60) {
        if (flock($lock, LOCK_EX | LOCK_NB)) {
            $acquired = true;
            break;
        }
        usleep(300000);
        $tries++;
    }

    if (!$acquired) {
        fclose($lock);
        return 'سیستم مشغول است. چند لحظه دیگر پیام بدهید.';
    }

    try {
        $payload = [
            'model' => $model,
            'messages' => $messages,
            'temperature' => TEMPERATURE,
            'stream' => false,
        ];

        $ch = curl_init(AI_API_URL);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($payload),
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Authorization: Bearer ' . AI_API_KEY,
            ],
            CURLOPT_TIMEOUT => 120,
            CURLOPT_CONNECTTIMEOUT => 15,
        ]);
        $raw = curl_exec($ch);
        $httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $err = curl_error($ch);
        curl_close($ch);

        if ($raw === false || $httpCode >= 400) {
            return 'خطا در ارتباط با مدل. کد: ' . $httpCode . ($err ? " ($err)" : '');
        }

        $json = json_decode($raw, true);
        $content = $json['choices'][0]['message']['content'] ?? null;
        if (!$content) {
            return 'پاسخ خالی از مدل دریافت شد.';
        }
        return trim($content);
    } finally {
        flock($lock, LOCK_UN);
        fclose($lock);
    }
}

function escapeHtml(string $text): string {
    return htmlspecialchars($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}

function formatReply(string $text): string {
    $text = preg_replace('/```(\w*)\n([\s\S]*?)```/', "\n<pre>$2</pre>\n", $text);
    $text = preg_replace('/`([^`]+)`/', '<code>$1</code>', $text);
    $text = preg_replace('/\*\*(.+?)\*\*/', '<b>$1</b>', $text);
    $text = preg_replace('/\*(.+?)\*/', '<i>$1</i>', $text);
    return $text;
}

function isPrivate(array $chat): bool {
    return ($chat['type'] ?? '') === 'private';
}

function isGroup(array $chat): bool {
    $type = $chat['type'] ?? '';
    return $type === 'group' || $type === 'supergroup';
}

function isBotMentioned(string $text): bool {
    $username = strtolower(BOT_USERNAME);
    return stripos($text, '@' . $username) !== false;
}

function isReplyToBot(array $message): bool {
    $reply = $message['reply_to_message'] ?? null;
    if (!$reply) {
        return false;
    }
    $from = $reply['from'] ?? [];
    if (!empty($from['is_bot']) && strtolower($from['username'] ?? '') === strtolower(BOT_USERNAME)) {
        return true;
    }
    return false;
}

function cleanMention(string $text): string {
    $username = BOT_USERNAME;
    $text = preg_replace('/@' . preg_quote($username, '/') . '/iu', '', $text);
    return trim($text);
}

function handleStartPrivate(int|string $chatId, string $name): void {
    $text = "سلام <b>" . escapeHtml($name) . "</b> 👋\n\n"
          . "به <b>Taha AI</b> خوش اومدی.\n"
          . "منوی زیر رو استفاده کن یا مستقیم پیام بفرست.";
    sendMessage($chatId, $text, ['reply_markup' => mainMenuKeyboard()]);
}

function handleStartGroup(int|string $chatId): void {
    $text = "👋 <b>Taha AI</b> به گروه اضافه شد.\n\n"
          . "برای سوال پرسیدن من رو منشن کن (@" . BOT_USERNAME . ")\n"
          . "یا به پیام‌هام ریپلای بزن.\n\n"
          . "هر پیام Thinking می‌گیره و یکی‌یکی جواب داده می‌شه.\n"
          . "فقط دکمه پاک‌سازی حافظه گروه فعاله.";
    sendMessage($chatId, $text, ['reply_markup' => groupClearKeyboard()]);
}

function handleCallback(array $cb): void {
    $data = $cb['data'] ?? '';
    $chat = $cb['message']['chat'] ?? [];
    $chatId = $chat['id'];
    $msgId = $cb['message']['message_id'];
    $callbackId = $cb['id'];
    $user = loadUser($chatId);
    $private = isPrivate($chat);

    if (!$private && $data !== 'clear' && $data !== 'help') {
        answerCallback($callbackId, 'این گزینه فقط در پیوی فعال است');
        return;
    }

    if ($data === 'menu' || $data === 'status') {
        answerCallback($callbackId);
        $model = $user['model'] ?? DEFAULT_MODEL;
        $count = count($user['messages'] ?? []);
        $text = "📊 <b>وضعیت فعلی</b>\n\n"
              . "مدل: <code>" . escapeHtml($model) . "</code>\n"
              . "تعداد پیام‌ها: <b>" . $count . "</b>\n"
              . "عنوان: " . escapeHtml($user['title'] ?? 'گفتگوی جدید');
        editMessage($chatId, $msgId, $text, ['reply_markup' => mainMenuKeyboard()]);
        return;
    }

    if ($data === 'newchat') {
        if (!$private) {
            answerCallback($callbackId, 'این گزینه فقط در پیوی فعال است');
            return;
        }
        resetChat($chatId);
        answerCallback($callbackId, 'گفتگوی جدید شروع شد');
        editMessage($chatId, $msgId, "✅ گفتگوی جدید آماده است.\nهر چی دوست داری بپرس.", ['reply_markup' => mainMenuKeyboard()]);
        return;
    }

    if ($data === 'clear') {
        resetChat($chatId);
        answerCallback($callbackId, 'حافظه پاک شد');
        $text = $private
            ? "🗑 تمام تاریخچه این چت پاک شد."
            : "🗑 حافظه گروه پاک شد.";
        $kb = $private ? mainMenuKeyboard() : groupClearKeyboard();
        editMessage($chatId, $msgId, $text, ['reply_markup' => $kb]);
        return;
    }

    if ($data === 'models') {
        if (!$private) {
            answerCallback($callbackId, 'تغییر مدل فقط در پیوی ممکن است');
            return;
        }
        answerCallback($callbackId);
        $current = $user['model'] ?? DEFAULT_MODEL;
        editMessage($chatId, $msgId, "🧠 مدل مورد نظرت رو انتخاب کن:", ['reply_markup' => modelsKeyboard($current)]);
        return;
    }

    if (str_starts_with($data, 'setmodel_')) {
        if (!$private) {
            answerCallback($callbackId, 'تغییر مدل فقط در پیوی ممکن است');
            return;
        }
        $model = substr($data, 9);
        if (in_array($model, AVAILABLE_MODELS, true)) {
            $user['model'] = $model;
            saveUser($chatId, $user);
            answerCallback($callbackId, 'مدل تغییر کرد: ' . $model);
            editMessage($chatId, $msgId, "✅ مدل تنظیم شد روی <code>" . escapeHtml($model) . "</code>", ['reply_markup' => mainMenuKeyboard()]);
        } else {
            answerCallback($callbackId, 'مدل نامعتبر');
        }
        return;
    }

    if ($data === 'help') {
        answerCallback($callbackId);
        if ($private) {
            $text = "ℹ️ <b>راهنمای Taha AI (پیوی)</b>\n\n"
                  . "• مستقیم پیام بفرست تا جواب بگیری\n"
                  . "• اول پیام Thinking میاد بعد ویرایش میشه\n"
                  . "• از منو می‌تونی مدل عوض کنی یا چت جدید بسازی\n"
                  . "• تاریخچه هر کاربر جدا ذخیره میشه\n"
                  . "• درخواست‌ها یکی‌یکی پردازش میشن تا کرش نشه";
            editMessage($chatId, $msgId, $text, ['reply_markup' => mainMenuKeyboard()]);
        } else {
            $text = "ℹ️ <b>راهنمای گروه</b>\n\n"
                  . "• منشن کن یا ریپلای بزن تا جواب بدم\n"
                  . "• به هر پیام Thinking فوری فرستاده می‌شه و یکی‌یکی ادیت می‌شه\n"
                  . "• حافظه گروه مشترک است\n"
                  . "• فقط پاک‌سازی حافظه فعال است";
            editMessage($chatId, $msgId, $text, ['reply_markup' => groupClearKeyboard()]);
        }
        return;
    }

    answerCallback($callbackId);
}

function processAIRequest(int|string $chatId, string $text, int $thinkingId): void {
    $user = loadUser($chatId);
    $model = $user['model'] ?? DEFAULT_MODEL;

    $history = $user['messages'] ?? [];
    $history[] = ['role' => 'user', 'content' => $text];

    $apiMessages = array_map(fn($m) => ['role' => $m['role'], 'content' => $m['content']], $history);

    $reply = callAI($apiMessages, $model);

    $history[] = ['role' => 'assistant', 'content' => $reply];
    if (count($history) > 40) {
        $history = array_slice($history, -40);
    }

    $user['messages'] = $history;
    if (($user['title'] ?? '') === 'گفتگوی جدید' || empty($user['title'])) {
        $user['title'] = mb_substr($text, 0, 40);
    }
    saveUser($chatId, $user);

    $formatted = formatReply(escapeHtml($reply));
    if (mb_strlen($formatted) > 4000) {
        $formatted = mb_substr($formatted, 0, 3990) . '…';
    }

    editMessage($chatId, $thinkingId, $formatted);
}

function handleMessage(array $message): void {
    $chat = $message['chat'] ?? [];
    $chatId = $chat['id'];
    $text = trim($message['text'] ?? '');
    $name = $message['from']['first_name'] ?? 'کاربر';
    $msgId = $message['message_id'] ?? 0;
    $private = isPrivate($chat);
    $group = isGroup($chat);

    if (!$private && !$group) {
        return;
    }

    if ($private) {
        if ($text === '/start' || $text === '/menu') {
            handleStartPrivate($chatId, $name);
            return;
        }

        if ($text === '/new' || $text === '/newchat') {
            resetChat($chatId);
            sendMessage($chatId, "✅ گفتگوی جدید شروع شد.", ['reply_markup' => mainMenuKeyboard()]);
            return;
        }

        if ($text === '/clear') {
            resetChat($chatId);
            sendMessage($chatId, "🗑 حافظه پاک شد.", ['reply_markup' => mainMenuKeyboard()]);
            return;
        }

        if ($text === '/models') {
            $user = loadUser($chatId);
            sendMessage($chatId, "🧠 مدل مورد نظرت رو انتخاب کن:", ['reply_markup' => modelsKeyboard($user['model'] ?? DEFAULT_MODEL)]);
            return;
        }

        if ($text === '/help') {
            $textHelp = "ℹ️ <b>راهنمای Taha AI (پیوی)</b>\n\n"
                      . "• مستقیم پیام بفرست\n"
                      . "• منو با /start\n"
                      . "• /new برای چت جدید\n"
                      . "• /models و /clear";
            sendMessage($chatId, $textHelp, ['reply_markup' => mainMenuKeyboard()]);
            return;
        }

        if ($text === '' || str_starts_with($text, '/')) {
            sendMessage($chatId, "دستور ناشناخته. از /start استفاده کن یا مستقیم پیام بفرست.", ['reply_markup' => mainMenuKeyboard()]);
            return;
        }

        $thinking = sendMessage($chatId, "⏳ <b>Thinking…</b>");
        $thinkingId = $thinking['result']['message_id'] ?? null;
        if (!$thinkingId) {
            sendMessage($chatId, "خطا در ارسال پیام Thinking.");
            return;
        }
        processAIRequest($chatId, $text, $thinkingId);
        return;
    }

    if ($group) {
        if ($text === '/start' || $text === '/menu' || $text === '/help') {
            handleStartGroup($chatId);
            return;
        }

        if ($text === '/clear') {
            resetChat($chatId);
            sendMessage($chatId, "🗑 حافظه گروه پاک شد.", [
                'reply_to_message_id' => $msgId,
                'reply_markup' => groupClearKeyboard(),
            ]);
            return;
        }

        if ($text === '/models' || str_starts_with($text, '/')) {
            return;
        }

        if ($text === '') {
            return;
        }

        $shouldReply = isBotMentioned($text) || isReplyToBot($message);
        if (!$shouldReply) {
            return;
        }

        $clean = cleanMention($text);
        if ($clean === '') {
            sendMessage($chatId, "چیزی نپرسیدی 😄", ['reply_to_message_id' => $msgId]);
            return;
        }

        $thinking = sendMessage($chatId, "⏳ <b>Thinking…</b>", [
            'reply_to_message_id' => $msgId,
        ]);
        $thinkingId = $thinking['result']['message_id'] ?? null;
        if (!$thinkingId) {
            return;
        }

        processAIRequest($chatId, $clean, $thinkingId);
    }
}

function handleMyChatMember(array $update): void {
    $member = $update['my_chat_member'] ?? null;
    if (!$member) {
        return;
    }

    $chat = $member['chat'] ?? [];
    $newStatus = $member['new_chat_member']['status'] ?? '';
    $oldStatus = $member['old_chat_member']['status'] ?? '';

    if (!isGroup($chat)) {
        return;
    }

    $chatId = $chat['id'];

    if (in_array($newStatus, ['member', 'administrator'], true) && in_array($oldStatus, ['left', 'kicked'], true)) {
        handleStartGroup($chatId);
    }
}

$input = file_get_contents('php://input');
$update = json_decode($input, true);

if (!$update) {
    http_response_code(200);
    echo 'ok';
    exit;
}

if (isset($update['callback_query'])) {
    handleCallback($update['callback_query']);
} elseif (isset($update['message'])) {
    handleMessage($update['message']);
} elseif (isset($update['my_chat_member'])) {
    handleMyChatMember($update);
}

http_response_code(200);
echo 'ok';