"""
AI Engineering Employee Platform V2
主入口 — FastAPI 应用
"""
import structlog
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from app.api.routes import router
from app.configs import settings

logger = structlog.get_logger()


@asynccontextmanager
async def lifespan(app: FastAPI):
    logger.info("AI Engineering Platform V2 starting up", debug=settings.debug)
    # DB init (optional - only if DB is configured)
    try:
        from app.db.database import init_db
        await init_db()
        logger.info("Database initialized")
    except Exception as e:
        logger.warning("Database init skipped", error=str(e))
    yield
    logger.info("Shutting down")


app = FastAPI(
    title="AI Engineering Employee Platform V2",
    description="""
## AI Engineering Employee Platform V2

An autonomous AI engineering team that can:
- **Analyze** project requirements
- **Design** system architecture
- **Develop** code using Claude, Codex, OpenHands, or Gemini
- **Test** automatically with pytest, npm test, go test, etc.
- **Review** code for bugs, security, and performance
- **Report** with full diff summary and PR description
- **Commit** to Git and create Pull Requests

### Workflow Types
- `engineering` — Full development pipeline
- `bugfix` — Bug diagnosis and fix
- `review` — Code review only
- `release` — Release preparation and PR creation
""",
    version="2.0.0",
    lifespan=lifespan,
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(router, prefix="/api/v1")


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "app.main:app",
        host=settings.api_host,
        port=settings.api_port,
        reload=settings.debug,
        log_level=settings.log_level.lower(),
    )
