"""Root CLI app for ossctx."""

import warnings
import typer

from codectx.cli import app as code_app
from docsctx.cli import app as docs_app
from otelctx.cli import app as otel_app
from ui.cli import app as ui_app
from common.version import __version__
import threading
from pathlib import Path
import uvicorn
from ui.app import build_app
from otelctx.db.repository import OtelRepository
from otelctx.api.routes import ingest_payload
from codectx.config import CodeSettings
from otelctx.config import OtelSettings
from docsctx.config import DocsSettings

app = typer.Typer(
    name="ossCtx",
    help="Unified CLI for code, docs, and otel context workflows.",
    no_args_is_help=True,
    invoke_without_command=True,
)
app.add_typer(code_app, name="code")
app.add_typer(docs_app, name="docs")
app.add_typer(otel_app, name="otel")
app.add_typer(ui_app, name="ui")


@app.callback()
def root_callback(version: bool = typer.Option(False, "--version", help="Show version and exit.")) -> None:
    """Root callback for global options."""
    if version:
        typer.echo(__version__)
        raise typer.Exit()


@app.command("version")
def version_cmd() -> None:
    """Show the installed ossCtx version."""
    typer.echo(__version__)


@app.command("serve")
def serve(
    host: str = typer.Option("127.0.0.1", "--host", help="Bind host."),
    port: int = typer.Option(8070, "--port", help="Bind port."),
    grpc_port: int = typer.Option(4317, "--grpc-port", help="OTLP gRPC port."),
    code_db: str = typer.Option(".codecontext.db", "--code-db", help="Path to the code context database."),
    docs_db: str = typer.Option(".docscontext.db", "--docs-db", help="Path to the docs context database."),
    otel_db: str = typer.Option(".otelcontext.db", "--otel-db", help="Path to the otel context database."),
) -> None:
    """Run the unified UI, APIs, and all MCP servers simultaneously."""
    typer.echo("🚀 Starting unified ossCtx server...")
    
    grpc_server = None
    if grpc_port > 0:
        try:
            from otelctx.otlp_grpc import start_otlp_grpc_server
            otel_repo = OtelRepository(Path(otel_db))
            otel_repo.create_schema()
            grpc_server = start_otlp_grpc_server(
                grpc_port,
                lambda payload: ingest_payload(otel_repo, payload),
            )
            typer.echo(f"  OTLP gRPC receiver listening on 0.0.0.0:{grpc_port}")
        except RuntimeError as exc:
            typer.echo(f"  OTLP gRPC disabled: {exc}")

    try:
        from common.middleware import configure_structured_logging
        configure_structured_logging()

        typer.echo(f"🌐 Starting unified UI, API, and MCP server on {host}:{port}...")
        typer.echo(f"  MCP Code URL:    http://{host}:{port}/mcp/code")
        typer.echo(f"  MCP Docs URL:    http://{host}:{port}/mcp/docs")
        typer.echo(f"  MCP Otel URL:    http://{host}:{port}/mcp/otel")
        typer.echo(f"  MCP Unified URL: http://{host}:{port}/mcp/unified")
        typer.echo(f"  Context API:     http://{host}:{port}/api/context/assemble")
        typer.echo(f"  Transport:       Streamable HTTP (MCP SDK)")
        app_instance = build_app(code_db=Path(code_db), docs_db=Path(docs_db), otel_db=Path(otel_db))
        uvicorn.run(app_instance, host=host, port=port)
    finally:
        if grpc_server is not None:
            grpc_server.stop(grace=1)


def main() -> None:
    """Console entrypoint."""
    # Suppress noisy Pydantic V1 compat warning from langchain on Python 3.14+
    warnings.filterwarnings(
        "ignore",
        message="Core Pydantic V1 functionality",
        category=UserWarning,
    )
    app()
