from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.core.database import engine, Base

# Importer ALLE modeller så create_all kender dem
from app.models import (
    User, Song, Dance, DanceLevel, Project, ProjectMember, ProjectSong,
    PlaylistShare, CommunityDance, CommunityDanceAlt, DanceAltRating,
    SongDance, SongAltDance,
)
from app.routers import auth, projects, songs, alternatives, dances, sync, sharing, live
from app.websocket.manager import router as ws_router

# Opret tabeller hvis de ikke findes
Base.metadata.create_all(bind=engine)

app = FastAPI(
    title="Linedance API",
    version="0.1.0",
    description="Backend for linedance-afspiller og projektstyring",
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],   # Stram til i produktion
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(auth.router)
app.include_router(projects.router)
app.include_router(songs.router)
app.include_router(alternatives.router)
app.include_router(dances.router)
app.include_router(sync.router)
app.include_router(sharing.router)
app.include_router(live.router)


@app.on_event("startup")
def seed_dance_levels():
    """Opret standard dans-niveauer hvis tabellen er tom."""
    from sqlalchemy.orm import Session
    from app.models import DanceLevel
    with Session(engine) as db:
        if db.query(DanceLevel).count() == 0:
            defaults = [
                DanceLevel(sort_order=10, name="Absolute Beginner", description="Ingen tidligere danse-erfaring kræves"),
                DanceLevel(sort_order=20, name="Beginner",          description="Lidt tidligere erfaring"),
                DanceLevel(sort_order=30, name="High Beginner",     description="God begynder, klar til mere"),
                DanceLevel(sort_order=40, name="Low Improver",      description="Begyndende øvet"),
                DanceLevel(sort_order=50, name="Improver",          description="Grundlæggende færdigheder på plads"),
                DanceLevel(sort_order=60, name="High Improver",     description="Stærk øvet, næsten intermediate"),
                DanceLevel(sort_order=70, name="Low Intermediate",  description="Begyndende intermediate"),
                DanceLevel(sort_order=80, name="Intermediate",      description="Erfaren danser"),
                DanceLevel(sort_order=90, name="High Intermediate", description="Stærk intermediate"),
                DanceLevel(sort_order=99, name="Advanced",          description="Fuld beherskelse af trin og teknik"),
            ]
            db.add_all(defaults)
            db.commit()
app.include_router(ws_router)


@app.get("/")
def root():
    return {"status": "ok", "service": "Linedance API"}
