"""
OpenTester Backend - FastAPI + MCP Server
"""
import logging

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from opentester.api import projects, cases, execution, parser, templates
from opentester.core.config import ensure_data_dirs
from opentester.mcp import mcp

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)

ensure_data_dirs()

app = FastAPI(
    title="OpenTester",
    description="AI-driven end-to-end testing platform",
    version="0.1.0",
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:5173"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# API routes (for Web UI)
app.include_router(projects.router, prefix="/api/projects", tags=["projects"])
app.include_router(cases.router, prefix="/api/cases", tags=["cases"])
app.include_router(execution.router, prefix="/api/execution", tags=["execution"])
app.include_router(parser.router, prefix="/api/parser", tags=["parser"])
app.include_router(templates.router, prefix="/api/templates", tags=["templates"])


# MCP endpoint (for Claude Code)
# Note: streamable_http_app must be run via mcp.run(), not mounted directly
# Use /mcp endpoint that forwards to MCP server


@app.get("/health")
async def health_check():
    return {"status": "ok", "service": "opentester"}


@app.get("/")
async def root():
    return {"name": "OpenTester", "version": "0.1.0", "docs": "/docs"}


def main():
    """Entry point for uv run."""
    import uvicorn
    uvicorn.run("opentester.main:app", host="127.0.0.1", port=8000, reload=True)
