{% extends "base.html" %}
{% block title %}Brain MCP — Setup Wizard{% endblock %}

{% block content %}
<div x-data="onboardingWizard()" x-init="init()">

    <!-- Progress bar -->
    <hgroup>
        <h1>🧠 Brain MCP Setup</h1>
        <p>Step <span x-text="step"></span> of 5</p>
    </hgroup>
    <progress :value="step" max="5"></progress>

    <!-- ═══════════════════════════════════════ -->
    <!-- STEP 1: Discover Sources               -->
    <!-- ═══════════════════════════════════════ -->
    <div x-show="step === 1" x-transition>
        <article>
            <header><strong>📁 Step 1: Discover Sources</strong></header>
            <p>Let's find your AI conversation data. We'll scan common locations on your machine.</p>

            <div id="discover-results"
                 hx-get="/api/sources/discover"
                 hx-trigger="load"
                 hx-swap="innerHTML">
                <p aria-busy="true">Scanning for sources...</p>
            </div>

            <footer>
                <div style="display: flex; justify-content: flex-end; gap: 0.5rem;">
                    <button @click="nextStep()">
                        Next →
                    </button>
                </div>
            </footer>
        </article>
    </div>

    <!-- ═══════════════════════════════════════ -->
    <!-- STEP 2: Ingest Data                    -->
    <!-- ═══════════════════════════════════════ -->
    <div x-show="step === 2" x-transition>
        <article>
            <header><strong>📥 Step 2: Import Conversations</strong></header>
            <p>Import your conversations into Brain MCP. This may take a moment depending on volume.</p>

            <!-- Discovered sources summary -->
            <div id="discovered-sources-summary" x-show="discoveredSources.length > 0" x-cloak>
                <h6>Discovered Sources</h6>
                <template x-for="src in discoveredSources" :key="src.source_type">
                    <div style="display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0.5rem;">
                        <span>✅</span>
                        <strong x-text="src.display_name"></strong>
                        <small x-text="src.paths.length + ' location(s)'" style="color: var(--muted-color);"></small>
                    </div>
                </template>
                <hr>
            </div>

            <div id="ingest-area">
                <button hx-post="/api/sources/sync-all"
                        hx-target="#ingest-progress"
                        hx-swap="innerHTML">
                    🔄 Start Import
                </button>
                <div id="ingest-progress" style="margin-top: 1rem;"></div>
            </div>

            <footer>
                <div style="display: flex; justify-content: space-between;">
                    <button class="outline" @click="prevStep()">← Back</button>
                    <button @click="nextStep()">Next →</button>
                </div>
            </footer>
        </article>
    </div>

    <!-- ═══════════════════════════════════════ -->
    <!-- STEP 3: Configure Embedding            -->
    <!-- ═══════════════════════════════════════ -->
    <div x-show="step === 3" x-transition>
        <article>
            <header><strong>🔗 Step 3: Configure Embedding</strong></header>
            <p>Embeddings enable semantic search — finding conversations by meaning, not just keywords.</p>

            <fieldset>
                <legend><strong>Embedding Provider</strong></legend>
                <label>
                    <input type="radio" name="embedding" value="local"
                           x-model="embeddingProvider">
                    <strong>Local (nomic-embed)</strong>
                    <br><small>Free, runs on your machine. Slower first run (~10 min) while model downloads.</small>
                </label>
                <label>
                    <input type="radio" name="embedding" value="openrouter"
                           x-model="embeddingProvider">
                    <strong>OpenRouter API</strong>
                    <br><small>Fast, requires API key. Small cost per batch.</small>
                </label>
                <label>
                    <input type="radio" name="embedding" value="skip"
                           x-model="embeddingProvider">
                    <strong>Skip for now</strong>
                    <br><small>You can enable this later in Settings. Keyword search will still work.</small>
                </label>
            </fieldset>

            <!-- API key input for OpenRouter -->
            <div x-show="embeddingProvider === 'openrouter'" x-transition>
                <label>
                    OpenRouter API Key
                    <input type="password" x-model="openrouterKey"
                           placeholder="sk-or-...">
                </label>
                <button class="outline secondary"
                        @click="validateKey()"
                        x-text="keyValidating ? 'Checking...' : 'Validate Key'"
                        :disabled="keyValidating || !openrouterKey"
                        :aria-busy="keyValidating">
                </button>
                <small x-show="keyStatus === 'valid'" style="color: #3fb950;">✅ Key is valid</small>
                <small x-show="keyStatus === 'invalid'" style="color: #f85149;">❌ Invalid key</small>
            </div>

            <footer>
                <div style="display: flex; justify-content: space-between;">
                    <button class="outline" @click="prevStep()">← Back</button>
                    <button @click="saveEmbedding(); nextStep()">Next →</button>
                </div>
            </footer>
        </article>
    </div>

    <!-- ═══════════════════════════════════════ -->
    <!-- STEP 4: Configure Summaries            -->
    <!-- ═══════════════════════════════════════ -->
    <div x-show="step === 4" x-transition>
        <article>
            <header><strong>📝 Step 4: Configure Summaries</strong></header>
            <p>Summaries power the cognitive prosthetic tools — domain tracking, open threads, and context recovery.</p>

            <fieldset>
                <legend><strong>Summary Provider</strong></legend>
                <label>
                    <input type="radio" name="summaries" value="gemini"
                           x-model="summaryProvider">
                    <strong>Gemini (free tier)</strong>
                    <br><small>Google's free API tier. Good quality, rate-limited.</small>
                </label>
                <label>
                    <input type="radio" name="summaries" value="openrouter"
                           x-model="summaryProvider">
                    <strong>OpenRouter API</strong>
                    <br><small>Multiple models, requires API key.</small>
                </label>
                <label>
                    <input type="radio" name="summaries" value="skip"
                           x-model="summaryProvider">
                    <strong>Skip for now</strong>
                    <br><small>Search and basic tools will still work. Prosthetic tools need summaries.</small>
                </label>
            </fieldset>

            <footer>
                <div style="display: flex; justify-content: space-between;">
                    <button class="outline" @click="prevStep()">← Back</button>
                    <button @click="saveSummaries(); nextStep()">Next →</button>
                </div>
            </footer>
        </article>
    </div>

    <!-- ═══════════════════════════════════════ -->
    <!-- STEP 5: Connect to Claude              -->
    <!-- ═══════════════════════════════════════ -->
    <div x-show="step === 5" x-transition>
        <article>
            <header><strong>🔌 Step 5: Connect to Claude</strong></header>
            <p>Add Brain MCP to your AI client. Copy this config snippet:</p>

            <div id="mcp-config-display"
                 hx-get="/api/onboarding/mcp-config/snippet"
                 hx-trigger="load"
                 hx-swap="innerHTML">
                <p aria-busy="true">Generating config...</p>
            </div>

            <p><strong>Or auto-configure:</strong></p>
            <div class="grid">
                <button class="outline"
                        hx-post="/api/onboarding/auto-configure"
                        hx-vals='{"target": "claude-desktop"}'
                        hx-target="#auto-config-result"
                        hx-swap="innerHTML">
                    Claude Desktop
                </button>
                <button class="outline"
                        hx-post="/api/onboarding/auto-configure"
                        hx-vals='{"target": "claude-code"}'
                        hx-target="#auto-config-result"
                        hx-swap="innerHTML">
                    Claude Code
                </button>
                <button class="outline"
                        hx-post="/api/onboarding/auto-configure"
                        hx-vals='{"target": "cursor"}'
                        hx-target="#auto-config-result"
                        hx-swap="innerHTML">
                    Cursor
                </button>
            </div>
            <div id="auto-config-result" style="margin-top: 0.5rem;"></div>

            <hr>

            <!-- Stats summary -->
            <div id="onboarding-stats"
                 hx-get="/api/stats/overview.json"
                 hx-trigger="load"
                 hx-swap="none"
                 hx-on::after-request="
                    try {
                        const d = JSON.parse(event.detail.xhr.responseText);
                        document.getElementById('stat-messages').textContent = d.messages?.toLocaleString() || '0';
                        document.getElementById('stat-embedded').textContent = d.embedded?.toLocaleString() || '0';
                        document.getElementById('stat-summaries').textContent = d.summaries?.toLocaleString() || '0';
                    } catch(e) {}
                 ">
            </div>
            <div class="grid">
                <div>
                    <strong id="stat-messages">—</strong>
                    <br><small>Messages imported</small>
                </div>
                <div>
                    <strong id="stat-embedded">—</strong>
                    <br><small>Embedded</small>
                </div>
                <div>
                    <strong id="stat-summaries">—</strong>
                    <br><small>Summaries</small>
                </div>
            </div>

            <footer>
                <div style="display: flex; justify-content: space-between;">
                    <button class="outline" @click="prevStep()">← Back</button>
                    <button @click="finishOnboarding()">
                        🎉 Go to Dashboard
                    </button>
                </div>
            </footer>
        </article>
    </div>

</div>
{% endblock %}

{% block scripts %}
<script>
function onboardingWizard() {
    return {
        step: 1,
        embeddingProvider: 'local',
        summaryProvider: 'skip',
        openrouterKey: '',
        keyValidating: false,
        keyStatus: '',  // '', 'valid', 'invalid'
        discoveredSources: [],

        async init() {
            try {
                const resp = await fetch('/api/onboarding/status');
                const data = await resp.json();
                if (data.complete) {
                    window.location.href = '/';
                    return;
                }
                this.step = data.current_step || 1;
            } catch(e) {}

            // Fetch discovered sources for step 2 display
            try {
                const discResp = await fetch('/api/onboarding/discover');
                if (discResp.ok) {
                    this.discoveredSources = await discResp.json();
                }
            } catch(e) {}
        },

        nextStep() {
            if (this.step < 5) {
                this.step++;
                this.saveStep();
            }
        },

        prevStep() {
            if (this.step > 1) {
                this.step--;
                this.saveStep();
            }
        },

        async saveStep() {
            try {
                await fetch('/api/onboarding/step/' + this.step, { method: 'POST' });
            } catch(e) {}
        },

        async validateKey() {
            this.keyValidating = true;
            this.keyStatus = '';
            try {
                const resp = await fetch('/api/settings/validate-key', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ key: this.openrouterKey }),
                });
                const data = await resp.json();
                this.keyStatus = data.valid ? 'valid' : 'invalid';
            } catch(e) {
                this.keyStatus = 'invalid';
            }
            this.keyValidating = false;
        },

        async saveEmbedding() {
            try {
                await fetch('/api/onboarding/configure-embedding', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        provider: this.embeddingProvider,
                        api_key: this.openrouterKey,
                    }),
                });
            } catch(e) {}
        },

        async saveSummaries() {
            try {
                await fetch('/api/onboarding/configure-summaries', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ provider: this.summaryProvider }),
                });
            } catch(e) {}
        },

        async finishOnboarding() {
            try {
                await fetch('/api/onboarding/complete', { method: 'POST' });
            } catch(e) {}
            window.location.href = '/';
        },
    };
}
</script>
{% endblock %}
