from __future__ import annotations
from typing import Annotated

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

from app.api import auth, dashboard, financial_management, master_data, procurement, reports, users
from app.core.config import settings
from app.core.i18n import Language, get_language, translate
from app.db.master_data import upsert_budget_heads, upsert_item_master, upsert_ofes_establishments
from app.db.migrations import apply_master_format_migrations
from app.db.report_data import upsert_default_report_allocations
from app.db.session import Base, SessionLocal, engine


Base.metadata.create_all(bind=engine)
apply_master_format_migrations(engine)
with SessionLocal() as db:
    upsert_budget_heads(db)
    upsert_item_master(db)
    upsert_ofes_establishments(db)
    upsert_default_report_allocations(db)
    db.commit()

app = FastAPI(title=settings.APP_NAME, version="1.0.0")

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

app.include_router(auth.router, prefix="/api/auth", tags=["Authentication"])
app.include_router(users.router, prefix="/api/users", tags=["Users"])
app.include_router(master_data.router, prefix="/api/master-data", tags=["Master Data"])
app.include_router(procurement.router, prefix="/api/procurement", tags=["Procurement Lifecycle"])
app.include_router(dashboard.router, prefix="/api/dashboard", tags=["Dashboard"])
app.include_router(reports.router, prefix="/api/reports", tags=["Reports"])
app.include_router(financial_management.router, prefix="/api/financial-management", tags=["Financial Management"])


@app.get("/api/health")
def health_check(language: Annotated[Language, Depends(get_language)]):
    return {"status": translate("health.ok", language), "service": settings.APP_NAME}
