using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using WikipediaRagWinForms.Rag;
using WikipediaRagWinForms.Services;

namespace WikipediaRagWinForms
{
    public partial class MainForm : Form
    {
        private CancellationTokenSource _cts;

        public MainForm()
        {
            InitializeComponent();

            this.Font = new System.Drawing.Font("Segoe UI", 11F);
            statusLabel.Text = "Bereit";

            // Modelle eintragen
            cmbModel.Items.Add("gemma3:4b");
            cmbModel.Items.Add("gemma3:12b");
            cmbModel.Items.Add("qwen2.5:7b");
            cmbModel.SelectedIndex = 0; // Standard: 4b
        }

        private async void btnAsk_Click(object sender, EventArgs e)
        {
            string question = txtQuestion.Text.Trim();
            string model = cmbModel.SelectedItem?.ToString() ?? "gemma3:12b";

            if (string.IsNullOrWhiteSpace(question))
            {
                MessageBox.Show("Bitte eine Frage eingeben.");
                return;
            }

            if (string.IsNullOrWhiteSpace(model))
                model = "gemma3:12b";

            // RagEngine mit aktuellem Modell erzeugen
            var rag = new RagEngine(
                new WikipediaOnlineClient(),
                new OllamaClient("http://127.0.0.1:11434/api", model)
            );

            _cts?.Cancel();
            _cts = new CancellationTokenSource();

            try
            {
                btnAsk.Enabled = false;
                txtAnswer.Clear();
                statusLabel.Text = "Verarbeite...";
                Cursor = Cursors.WaitCursor;

                // --- STREAMING-AUSGABE ---
                string lang = "de";
                if (rbEN.Checked) lang = "en";
                if (rbES.Checked) lang = "es";

                await rag.AskStreamAsync
                (
                    question,
                    model,
                    lang,     // <-- NEU
                    chunk =>
                    {
                        this.Invoke((Action)(() =>
                        {
                            txtAnswer.AppendText(chunk);
                        }));
                    },
                    _cts.Token
                );
                
                await Task.Delay(30);
                statusLabel.Text = "Fertig.";

            }
            catch (Exception ex)
            {
                txtAnswer.Text = "Fehler:\r\n" + ex.ToString();
                statusLabel.Text = "Fehler.";
            }
            finally
            {
                Cursor = Cursors.Default;
                btnAsk.Enabled = true;
            }
        }
    }
}

