"""FastAPI application for Whisper Scribe."""

from pathlib import Path
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse, FileResponse

from . import __version__, __app_name__
from .routes.transcribe import router as transcribe_router
from .routes.settings import router as settings_router

# Static files directory
STATIC_DIR = Path(__file__).parent / "static"

app = FastAPI(
    title=__app_name__,
    description="YouTube video transcription using OpenAI Whisper",
    version=__version__
)

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

# API routes
app.include_router(transcribe_router, prefix="/api")
app.include_router(settings_router, prefix="/api")


@app.get("/api")
async def api_info():
    """API information endpoint."""
    return {
        "name": __app_name__,
        "version": __version__,
        "description": "YouTube video transcription service"
    }


# Serve static files if they exist
if STATIC_DIR.exists() and (STATIC_DIR / "index.html").exists():
    app.mount("/assets", StaticFiles(directory=STATIC_DIR / "assets"), name="assets")

    @app.get("/{full_path:path}")
    async def serve_spa(request: Request, full_path: str):
        """Serve the SPA for all non-API routes."""
        # Don't intercept API routes
        if full_path.startswith("api"):
            return None

        # Try to serve the exact file
        file_path = STATIC_DIR / full_path
        if file_path.exists() and file_path.is_file():
            return FileResponse(file_path)

        # Fall back to index.html for SPA routing
        return FileResponse(STATIC_DIR / "index.html")
else:
    # Development mode - serve a simple page pointing to Vite dev server
    @app.get("/", response_class=HTMLResponse)
    async def dev_index():
        return """
        <!DOCTYPE html>
        <html>
        <head>
            <title>Whisper Scribe - Development Mode</title>
            <style>
                body {
                    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    min-height: 100vh;
                    margin: 0;
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    color: white;
                }
                .container {
                    text-align: center;
                    padding: 2rem;
                    background: rgba(255,255,255,0.1);
                    border-radius: 1rem;
                    backdrop-filter: blur(10px);
                }
                h1 { margin-bottom: 0.5rem; }
                p { opacity: 0.9; }
                code {
                    background: rgba(0,0,0,0.2);
                    padding: 0.2rem 0.5rem;
                    border-radius: 0.25rem;
                }
                a { color: #ffd700; }
            </style>
        </head>
        <body>
            <div class="container">
                <h1>Whisper Scribe</h1>
                <p>API is running at <code>/api</code></p>
                <p>For the full UI, run the frontend dev server:</p>
                <p><code>cd frontend && npm run dev</code></p>
                <p>Then open <a href="http://localhost:5173">http://localhost:5173</a></p>
            </div>
        </body>
        </html>
        """
