"""Setup wizard endpoints — first-run configuration."""

from __future__ import annotations

from fastapi import APIRouter, Request
from pydantic import BaseModel

from local_llm.ollama_client import OllamaClient

router = APIRouter(prefix="/setup", tags=["setup"])


@router.get("/status")
async def setup_status(request: Request):
    """Check if the system is configured and ready."""
    db = request.app.state.db
    settings = request.app.state.settings

    connections = await db.execute("SELECT COUNT(*) as cnt FROM v3q_config.database_connections")
    tables = await db.execute("SELECT COUNT(*) as cnt FROM v3q_config.table_registry")

    has_connections = connections[0]["cnt"] > 0 if connections else False
    has_tables = tables[0]["cnt"] > 0 if tables else False
    has_api_key = bool(settings.claude.api_key)

    ollama = OllamaClient(settings.ollama)
    ollama_available = await ollama.is_available()

    return {
        "is_configured": has_connections and has_tables and has_api_key,
        "has_connections": has_connections,
        "has_tables": has_tables,
        "has_api_key": has_api_key,
        "ollama_available": ollama_available,
        "connection_count": connections[0]["cnt"] if connections else 0,
        "table_count": tables[0]["cnt"] if tables else 0,
    }


@router.get("/preflight")
async def preflight_check(request: Request):
    """Run preflight checks and return results as JSON.

    Returns all checks with pass/fail status, error messages, and fixes.
    The frontend can display this during setup or on a diagnostics page.
    """
    from preflight import run_preflight
    result = await run_preflight()
    return {
        "ok": not result.has_critical_errors,
        "passed": result.passed,
        "errors": [
            {
                "component": e.component,
                "message": e.message,
                "fix": e.fix,
                "critical": e.critical,
            }
            for e in result.errors
        ],
    }


@router.get("/odbc")
async def list_odbc_dsns(request: Request):
    """List available ODBC data sources (legacy — use /discover-connections instead)."""
    from discovery.odbc_discovery import ODBCDiscovery
    return await ODBCDiscovery.list_dsns()


@router.get("/discover-connections")
async def discover_connections(request: Request, scan_network: bool = False):
    """Auto-discover database connections from ODBC, DBeaver, SSMS, etc.

    Users can select a discovered connection and only need to provide credentials.
    Set scan_network=true to also probe for SQL Server instances on the LAN (slower).
    """
    from discovery.odbc_discovery import ConnectionDiscovery
    discovery = ConnectionDiscovery()
    return await discovery.discover_all(scan_network=scan_network)


class TestOllamaRequest(BaseModel):
    base_url: str | None = None
    model: str | None = None


@router.post("/test-ollama")
async def test_ollama(request: Request, body: TestOllamaRequest | None = None):
    """Test Ollama connectivity."""
    from config import OllamaSettings
    settings = request.app.state.settings
    ollama_settings = OllamaSettings(
        base_url=body.base_url or settings.ollama.base_url if body else settings.ollama.base_url,
        model=body.model or settings.ollama.model if body else settings.ollama.model,
    )
    ollama = OllamaClient(ollama_settings)
    available = await ollama.is_available()
    if available:
        # Quick test
        try:
            response = await ollama.generate("Say 'Hello from V3Q.AI' in one sentence.", max_tokens=50)
            return {"status": "ok", "response": response.strip()}
        except Exception as e:
            return {"status": "error", "message": str(e)}
    return {"status": "unavailable", "message": "Ollama is not running or model not loaded"}


@router.post("/test-claude")
async def test_claude(request: Request):
    """Test Claude API connectivity.

    Routes through SecurityGateway — never imports anthropic directly.
    Frontend must show confirmation dialog before calling this endpoint.
    """
    settings = request.app.state.settings
    if not settings.claude.api_key:
        return {"status": "error", "message": "No API key configured"}

    try:
        from security.audit_log import AuditLog
        from security.gateway import SecurityGateway

        db = request.app.state.db
        audit = AuditLog(db)
        gateway = SecurityGateway(settings, audit)
        response = await gateway.send_to_claude(
            system_prompt="You are V3Q.AI connectivity test.",
            messages=[{"role": "user", "content": "Respond with exactly: V3Q.AI connection successful"}],
            metadata={"purpose": "connectivity_test"},
        )
        return {"status": "ok", "response": response.strip()}
    except Exception as e:
        return {"status": "error", "message": str(e)}


@router.get("/logs")
async def get_logs(request: Request, level: str = "WARNING", limit: int = 100):
    """Get recent log entries — for feeding into Claude Code for debugging.

    Returns JSON-lines format that can be directly piped to Claude Code.
    """
    from pathlib import Path
    import json

    log_file = Path("logs/v3q_errors.jsonl") if level == "WARNING" else Path("logs/v3q_app.jsonl")
    if not log_file.exists():
        return {"logs": [], "count": 0}

    logs = []
    with open(log_file, "r") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            try:
                entry = json.loads(line)
                logs.append(entry)
            except json.JSONDecodeError:
                continue

    # Return most recent entries
    logs = logs[-limit:]
    return {"logs": logs, "count": len(logs)}


@router.get("/logs/export")
async def export_logs(request: Request):
    """Export all error logs as a single text block for Claude Code analysis.

    Usage on target machine:
      curl http://server:8000/api/setup/logs/export > errors.jsonl
      # Then on dev machine with Claude Code:
      cat errors.jsonl | claude "Analyze these V3Q.AI errors and suggest fixes"
    """
    from pathlib import Path
    from fastapi.responses import PlainTextResponse

    log_file = Path("logs/v3q_errors.jsonl")
    if not log_file.exists():
        return PlainTextResponse("No error logs found.", media_type="text/plain")

    content = log_file.read_text(encoding="utf-8")
    return PlainTextResponse(content, media_type="application/x-ndjson")
