"""HTTP routes: health, config, transcribe, summarize."""

from __future__ import annotations

import asyncio
import json
import time

from aiohttp import web

from meeting_helper.state import state
from meeting_helper.server.websocket import ws_handler


async def health_handler(request: web.Request) -> web.Response:
    meeting_name = ""
    if state.meeting_info:
        meeting_name = getattr(state.meeting_info, "meeting_name", "") or ""
    return web.Response(
        text=json.dumps({
            "status": "ok",
            "meeting": meeting_name,
            "session_active": state.session_active,
            "uptime": round(time.time() - state.started_at) if state.started_at else 0,
        }),
        content_type="application/json",
    )


async def config_get_handler(request: web.Request) -> web.Response:
    """Return current workspace config."""
    config = request.app["config"]
    return web.Response(
        text=json.dumps({
            "repos": config.repos,
            "knowledge_path": config.knowledge_path,
        }),
        content_type="application/json",
    )


async def config_post_handler(request: web.Request) -> web.Response:
    """Update workspace config mid-session. Rebuilds system prompt."""
    try:
        body = await request.json()
    except Exception:
        return web.Response(status=400, text='{"error": "invalid JSON"}',
                            content_type="application/json")

    config = request.app["config"]
    changed = False

    if "repos" in body:
        config.repos = body["repos"]
        changed = True
    if "knowledge_path" in body:
        config.knowledge_path = body["knowledge_path"]
        changed = True

    if changed:
        from meeting_helper.ai.prompts import build_system_prompt
        knowledge_folders = body.get("knowledge_folders")
        if knowledge_folders is not None:
            from meeting_helper.context_loader import build_selective_context
            context_block = build_selective_context(
                config.repos, config.knowledge_path, knowledge_folders
            )
        else:
            from meeting_helper.context_loader import build_full_context
            context_block = build_full_context(config.repos, config.knowledge_path)
        state.system_prompt = build_system_prompt(context_block)

    return web.Response(
        text=json.dumps({"ok": True, "changed": changed}),
        content_type="application/json",
    )


async def transcript_handler_get(request: web.Request) -> web.Response:
    """GET /transcript — return the last N sentences from the buffer."""
    n = int(request.query.get("n", "10"))
    sentences = []
    if state.sentence_buffer is not None:
        sentences = state.sentence_buffer.get_last_n(n)
    interim = None
    if state.sentence_buffer is not None:
        interim = state.sentence_buffer.get_interim()
    return web.Response(
        text=json.dumps({"sentences": sentences, "interim": interim}),
        content_type="application/json",
    )


async def last_response_handler(request: web.Request) -> web.Response:
    """GET /last_response — return the last AI response text."""
    return web.Response(
        text=json.dumps({"text": state.last_response or ""}),
        content_type="application/json",
    )


async def query_handler(request: web.Request) -> web.Response:
    """POST /query — send a manual text query to Claude."""
    try:
        body = await request.json()
    except Exception:
        return web.Response(status=400, text='{"error": "invalid JSON"}',
                            content_type="application/json")

    text = body.get("text", "").strip()
    if not text:
        return web.Response(status=400, text='{"error": "text required"}',
                            content_type="application/json")

    from meeting_helper.ai.client import handle_manual_query
    config = request.app["config"]

    try:
        await handle_manual_query(state, config, text)
        return web.Response(
            text=json.dumps({"ok": True}),
            content_type="application/json",
        )
    except Exception as exc:
        return web.Response(
            status=500,
            text=json.dumps({"error": str(exc)}),
            content_type="application/json",
        )


async def transcribe_handler(request: web.Request) -> web.Response:
    """POST /transcribe — transcribe an MP3 file with Whisper."""
    try:
        body = await request.json()
    except Exception:
        return web.Response(status=400, text='{"error": "invalid JSON"}',
                            content_type="application/json")

    mp3_path = body.get("mp3_path", "")
    if not mp3_path:
        return web.Response(status=400, text='{"error": "mp3_path required"}',
                            content_type="application/json")

    from meeting_helper.ai.client import transcribe_audio_file
    config = request.app["config"]

    try:
        transcript = await asyncio.to_thread(transcribe_audio_file, mp3_path, config)
        return web.Response(
            text=json.dumps({"ok": True, "transcript": transcript}),
            content_type="application/json",
        )
    except Exception as exc:
        return web.Response(
            status=500,
            text=json.dumps({"error": str(exc)}),
            content_type="application/json",
        )


async def summarize_handler(request: web.Request) -> web.Response:
    """POST /summarize — summarize a transcript with Claude."""
    try:
        body = await request.json()
    except Exception:
        return web.Response(status=400, text='{"error": "invalid JSON"}',
                            content_type="application/json")

    transcript_path = body.get("transcript_path", "")
    if not transcript_path:
        return web.Response(status=400, text='{"error": "transcript_path required"}',
                            content_type="application/json")

    from meeting_helper.ai.client import summarize_transcript
    config = request.app["config"]

    try:
        summary = await summarize_transcript(transcript_path, config)
        return web.Response(
            text=json.dumps({"ok": True, "summary": summary}),
            content_type="application/json",
        )
    except Exception as exc:
        return web.Response(
            status=500,
            text=json.dumps({"error": str(exc)}),
            content_type="application/json",
        )


async def knowledge_tree_handler(request: web.Request) -> web.Response:
    """GET /knowledge-tree — return folder structure of the knowledge base."""
    config = request.app["config"]
    if not config.knowledge_path:
        return web.Response(
            text=json.dumps({"tree": []}), content_type="application/json"
        )
    from meeting_helper.context_loader import get_knowledge_tree
    tree = get_knowledge_tree(config.knowledge_path)
    return web.Response(
        text=json.dumps({"tree": tree}), content_type="application/json"
    )


def setup_routes(app: web.Application) -> None:
    app.router.add_get("/health", health_handler)
    app.router.add_get("/config", config_get_handler)
    app.router.add_post("/config", config_post_handler)
    app.router.add_get("/knowledge-tree", knowledge_tree_handler)
    app.router.add_get("/transcript", transcript_handler_get)
    app.router.add_get("/last_response", last_response_handler)
    app.router.add_post("/query", query_handler)
    app.router.add_post("/transcribe", transcribe_handler)
    app.router.add_post("/summarize", summarize_handler)
    app.router.add_get("/ws", ws_handler)
