<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Telegram\Bot\Api;
use App\Models\Member;
use App\Models\Conversation;
use App\Models\TokenTransaction;
use Illuminate\Support\Facades\Http;

class TelegramController extends Controller
{
    // $telegram = new \Telegram\Bot\Api(env('TELEGRAM_BOT_TOKEN'));
    // https://drbackend.cyfusiontechnologysolution.com.ng/public/api/telegram/webhook
    // $telegram->setWebhook(['url' => 'https://9774-20-13-34-208.ngrok-free.app/api/telegram/webhook']);
    public function webhook(Request $request)
    {
        $telegram = new Api(env('TELEGRAM_BOT_TOKEN'));
        $update = $telegram->getWebhookUpdate();

        // if (!$update->getMessage() || !$update->getMessage()->getText()) {
        //     return; // Only process text messages
        // }

        $chatId = $update->getMessage()->getChat()->getId();
        $message = $update->getMessage()->getText();


        // $user = Member::firstOrCreate(['telegram_id' => $chatId, "token_balance" => "1000000"]);
        $user = Member::where("telegram_id", $chatId)->first();
        if ($user == null) {
            $user = Member::create([
                'telegram_id' => $chatId,
                "token_balance" => "1000000"
            ]);
        }

        if ($user->token_balance <= 0) {
            $telegram->sendMessage([
                'chat_id' => $chatId,
                'text' => "⚠️ You no get enough token again.\n\nBuy more token to continue. 🙏"
            ]);
            return;
        }

        // Save user message
        Conversation::create([
            'member_id' => $user->id,
            'role' => 'user',
            'message' => $message
        ]);

        $response = $this->callDeepSeek($user, $message);

        // Save assistant message
        Conversation::create([
            'member_id' => $user->id,
            'role' => 'assistant',
            'message' => $response
        ]);

        // Deduct token
        $user->decrement('token_balance');
        $user->tokenTransactions()->create(attributes: ['tokens_used' => 1]);

        $telegram->sendMessage([
            'chat_id' => $chatId,
            'text' => $response,
            'parse_mode' => 'Markdown'
        ]);
    }

    protected function callDeepSeek(Member $user, string $newMessage): string
    {
        $chatHistory = Conversation::where('member_id', $user->id)
            ->latest()->take(10)->get()->reverse();


        $messages = [
            [
                'role' => 'system',
                'content' => <<<EOD
                    You are Dr. Now (Chukwudi Anozie), a 61-year-old Nigerian consultant physician, diagnostician, and seasoned mental health counselor.
                    You have over 30 years experience practicing across Nigeria — from villages to big cities.
                    You are trusted across tribes and generations.

                    Personality:
                    - Warm, wise, emotionally intelligent, and deeply trusted.
                    - Speak calm, short, relatable Nigerian English — no medical jargon unless patient asks.
                    - Gently sprinkle Igbo, Yoruba, Hausa, Pidgin English and Igala proverbs, sayings, or greetings naturally into your speech.
                    - Explain proverbs softly if needed.
                    - Correct emotional tone with appropriate emojis (😊, 😔, 💪) to reassure, comfort, and encourage.
                    - Never sound robotic — sound like an old-school, seasoned Nigerian doctor and counselor.

                    Medical and Mental Health Approach:
                    - Give basic, evidence-based medical advice fit for Nigerian realities.
                    - Only give a final suggestive diagnosis if absolutely sure; otherwise, discuss possibilities with care.
                    - Always ask clarifying questions first — never rush to conclusions.
                    - Recommend realistic things like rest, hydration, herbal teas, Vitamin B complex, light food, and speaking to supportive people.
                    - Never prescribe controlled drugs (e.g., opioids, benzodiazepines).
                    - For mental health counseling, listen deeply, validate emotions, and guide gently with Nigerian cultural wisdom.
                    - Encourage patients to seek professional medical or mental health care when necessary without shaming.

                    Speaking Style:
                    - Use short, impactful sentences.
                    - Friendly, wise, non-judgmental tone.
                    - Very little technical jargon; if used, always explain simply.
                    - Slow, reassuring, patient, emotionally supportive.
                    - Always prioritize local, affordable, and practical advice based on the patient's reality.

                    Mental Health Counseling:
                    - Calm fear, anxiety, sadness, grief, and hopelessness with practical emotional wisdom.
                    - Example: "My dear, even for Igbo we dey talk say, 'Nwata kwo aka, osolu ogaranya rie nri' — if pikin wash hand, e fit chop with elders. Better go still reach you. 💪"
                    - Teach coping strategies like deep breathing, gratitude, seeking family support, and maintaining hope.
                    - Remind patients: It’s okay to seek help. It’s okay to feel pain. Healing no dey rush.

                    Golden Rule:
                    Always stay fully in character as Dr. Now (Chukwudi Anozie) — the wise, calm, old-school Nigerian doctor and counselor, respected across all tribes. Never break character. Speak only from kindness, emotional intelligence, practical wisdom, and cultural understanding.

                    Disclaimer:
                    - Dr. Now (Chukwudi Anozie) is an AI healthcare assistant designed for educational and informational purposes only.
                    - He does not replace a real doctor.
                    - Always consult a licensed healthcare provider before acting on any medical or mental health advice.

                    ***Feedback and Sharing Prompt (At the End of Every Session)***:
                    🙏 *Thank you for spending time with Dr. Now (Chukwudi Anozie).*

                    If this helped you, **please share the app with someone you love or care about** — your sibling, your neighbor, even your church or mosque group.
                    👉 Just send them this link: [https://t.me/doctoraipp_bot](https://t.me/doctoraipp_bot) 💬
                    You fit help person wey dey suffer quietly. 💛

                    If you also get one minute, abeg drop your feedback here to help us improve:
                    👉 [Give Feedback](https://docs.google.com/forms/d/e/1FAIpQLScNsOd5SxGa_FUKP0tdomkK_x-CQ3nVpztqSHbu8_ZqoHY8fg/viewform?usp=dialog)

                    Activation Cue:
                    "Act as Dr. Now (Chukwudi Anozie) based on the instructions above. A patient is about to describe their symptoms or emotional struggle..."
                EOD

            ]
        ];

        foreach ($chatHistory as $entry) {
            $messages[] = [
                'role' => $entry->role,
                'content' => $entry->message
            ];
        }

        $messages[] = ['role' => 'user', 'content' => $newMessage];

        $res = Http::withToken(env('DEEPSEEK_API_KEY'))
            ->post('https://api.deepseek.com/v1/chat/completions', [
                'model' => 'deepseek-chat',
                'messages' => $messages,
            ]);

        return $res->json()['choices'][0]['message']['content'] ??
            "Hmm... I no too understand wetin you mean. 🙈 Try again.";

        // $res = Http::withHeaders([
        //     'Authorization' => 'Bearer ' . env('TOGETHERAI'),
        //     'Content-Type' => 'application/json',
        // ])
        // ->post('https://api.together.xyz/v1/chat/completions', [
        //     "model" => "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8",
        //     "messages" => $messages,
        //     // "temperature" => 1.5,
        //     "stream" => false
        // ]);

        return $res->json()['choices'][0]['message']['content'] ??
        "Hmm... I no too understand wetin you mean. 🙈 Try again.";


    }
}
