from pathlib import Path

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

from backend.api import accounts, balance, banks, charts, import_api, settings_api
from backend.db.database import init_db

init_db()

app = FastAPI(title="Income Calculator", version="0.1.0")
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(banks.router)
app.include_router(accounts.router)
app.include_router(import_api.router)
app.include_router(balance.router)
app.include_router(charts.router)
app.include_router(settings_api.router)

# Статика Vue (собранная в frontend/dist)
static_path = Path(__file__).resolve().parent.parent / "frontend" / "dist"
if static_path.exists():
    app.mount("/assets", StaticFiles(directory=static_path / "assets"), name="assets")

    @app.get("/")
    def index():
        from fastapi.responses import FileResponse
        return FileResponse(static_path / "index.html")

    @app.get("/{full_path:path}")
    def serve_spa(full_path: str):
        from fastapi.responses import FileResponse
        if full_path.startswith("api/"):
            return FileResponse(static_path / "index.html")  # let API handle; this won't be hit
        f = static_path / full_path
        if f.is_file():
            return FileResponse(f)
        return FileResponse(static_path / "index.html")
else:
    @app.get("/")
    def root():
        return {"message": "Backend running. Build frontend: cd frontend && npm run build"}
