"""
Settings and Configuration API Routes for CodeContext server.

Handles server configuration, health checks, and project listing.
"""

import asyncio

from fastapi import APIRouter, Request, Query

from ..services.store_manager import get_store, list_projects
from ..services.background import (
    start_periodic_consolidation,
    stop_periodic_consolidation,
    set_config as set_background_config,
)
from ..gpu_utils import get_gpu_info


router = APIRouter()


def get_config(request: Request):
    """Get server config from app state."""
    return request.app.state.server_config


def get_default_config(request: Request):
    """Get default config from app state."""
    return request.app.state.default_config


def get_base_path(request: Request):
    """Get base path from app state."""
    return request.app.state.base_path


def save_config_to_disk(request: Request, config: dict):
    """Save config using app's save_config function."""
    request.app.state.save_config(config)


def get_process_existing_conflicts(request: Request):
    """Get the process_existing_conflicts_background function."""
    return request.app.state.process_existing_conflicts_background


@router.get("/health")
async def health(request: Request):
    """Health check with GPU info."""
    return {
        "status": "ok",
        "model": request.app.state.model_name,
        "device": request.app.state.device,
        "base_path": str(get_base_path(request)),
        "project_count": len(list_projects()),
        "gpu": get_gpu_info()
    }


@router.get("/api/settings")
async def get_settings(request: Request):
    """Get current server settings."""
    server_config = get_config(request)
    default_config = get_default_config(request)
    return {
        "auto_resolve_enabled": server_config.get("auto_resolve_enabled", False),
        "auto_consolidation": server_config.get("auto_consolidation", default_config["auto_consolidation"])
    }


@router.get("/api/settings/consolidation")
async def get_consolidation_settings(request: Request):
    """Get auto-consolidation settings."""
    server_config = get_config(request)
    default_config = get_default_config(request)
    return server_config.get("auto_consolidation", default_config["auto_consolidation"])


@router.post("/api/settings/consolidation")
async def set_consolidation_settings(
    request: Request,
    enabled: bool = Query(...),
    mode: str = Query(default="session"),
    periodic_minutes: int = Query(default=30),
    threshold: float = Query(default=0.5)
):
    """Update auto-consolidation settings."""
    server_config = get_config(request)
    server_config["auto_consolidation"] = {
        "enabled": enabled,
        "mode": mode,
        "periodic_minutes": periodic_minutes,
        "threshold": threshold
    }
    save_config_to_disk(request, server_config)

    # Update background service config
    set_background_config(server_config)

    # Start/stop periodic task based on settings
    if enabled and mode in ("periodic", "both"):
        start_periodic_consolidation(periodic_minutes)
    else:
        stop_periodic_consolidation()

    status = "enabled" if enabled else "disabled"
    print(f"[Server] Auto-consolidation {status} (mode={mode})")

    return server_config["auto_consolidation"]


@router.post("/api/settings/auto-resolve")
async def set_auto_resolve(request: Request, enabled: bool = Query(...)):
    """Enable/disable automatic conflict resolution."""
    server_config = get_config(request)
    server_config["auto_resolve_enabled"] = enabled
    save_config_to_disk(request, server_config)

    # Update background service config
    set_background_config(server_config)

    status = "enabled" if enabled else "disabled"
    print(f"[Server] Auto-resolve {status}")

    # When enabling, also process all existing pending conflicts
    existing_triggered = False
    if enabled:
        process_func = get_process_existing_conflicts(request)
        asyncio.create_task(process_func())
        existing_triggered = True

    return {
        "auto_resolve_enabled": enabled,
        "status": "saved",
        "processing_existing": existing_triggered
    }


@router.get("/api/settings/debug-mode")
async def get_debug_mode_setting(request: Request):
    """Get current debug mode setting."""
    server_config = get_config(request)
    return {"debug_mode": server_config.get("debug_mode", False)}


@router.post("/api/settings/debug-mode")
async def set_debug_mode(request: Request, enabled: bool = Query(...)):
    """
    Enable/disable debug mode for CLI session persistence.

    When debug mode is OFF (default): --no-session-persistence flag is added to
    CLI subprocess calls, preventing JSONL file creation.

    When debug mode is ON: The flag is omitted, allowing JSONL files to be
    created in ~/.claude/projects/ for debugging purposes.
    """
    server_config = get_config(request)
    server_config["debug_mode"] = enabled
    save_config_to_disk(request, server_config)
    status = "enabled" if enabled else "disabled"
    print(f"[Server] Debug mode {status}")

    return {"debug_mode": enabled, "status": "saved"}


@router.get("/api/settings/summary")
async def get_summary_settings(request: Request):
    """Get summary injection settings."""
    server_config = get_config(request)
    default_config = get_default_config(request)
    return server_config.get("summary", default_config["summary"])


@router.post("/api/settings/summary")
async def set_summary_settings(
    request: Request,
    enabled: bool = Query(...),
    auto_generate_on_session_end: bool = Query(default=True),
    full_regen_every_n_sessions: int = Query(default=0),
    full_regen_every_n_memories: int = Query(default=50),
    max_tokens: int = Query(default=1000),
    timeline_items: int = Query(default=10)
):
    """Update summary injection settings."""
    server_config = get_config(request)
    server_config["summary"] = {
        "enabled": enabled,
        "auto_generate_on_session_end": auto_generate_on_session_end,
        "full_regen_every_n_sessions": full_regen_every_n_sessions,
        "full_regen_every_n_memories": full_regen_every_n_memories,
        "max_tokens": max_tokens,
        "timeline_items": timeline_items
    }
    save_config_to_disk(request, server_config)

    status = "enabled" if enabled else "disabled"
    print(f"[Server] Summary injection {status}")

    return server_config["summary"]


@router.get("/projects")
async def get_projects():
    """List all projects with databases."""
    projects = list_projects()
    project_info = []
    for p in projects:
        store = get_store(p)
        project_info.append({
            "name": p,
            "memory_count": store.count(),
            "db_path": str(store.db_path)
        })
    return {
        "projects": project_info,
        "count": len(projects)
    }
