"""Simple FastAPI application for KaiserLift.

This module exposes two endpoints:

* ``GET /`` – serves a small HTML form for uploading a FitNotes CSV file.
* ``POST /upload`` – accepts the uploaded CSV, processes it with the core
  KaiserLift utilities and returns the full HTML page generated by
  :func:`gen_html_viewer`.

The application can be started with ``python -m kaiserlift.webapp`` which will
launch a Uvicorn development server.
"""

from __future__ import annotations

import os

from fastapi import FastAPI, File, UploadFile
from fastapi.responses import HTMLResponse

from .pipeline import pipeline


app = FastAPI()


@app.get("/", response_class=HTMLResponse)
async def index() -> HTMLResponse:
    """Return a simple upload form."""

    return HTMLResponse(
        """
        <!DOCTYPE html>
        <html>
            <head>
                <title>KaiserLift</title>
                <style>
                    :root {
                        --bg: #ffffff;
                        --fg: #000000;
                        --bg-alt: #f5f5f5;
                        --border: #ccc;
                    }
                    @media (prefers-color-scheme: dark) {
                        :root {
                            --bg: #121212;
                            --fg: #e0e0e0;
                            --bg-alt: #1e1e1e;
                            --border: #333;
                        }
                    }
                    [data-theme="dark"] {
                        --bg: #121212;
                        --fg: #e0e0e0;
                        --bg-alt: #1e1e1e;
                        --border: #333;
                    }
                    [data-theme="light"] {
                        --bg: #ffffff;
                        --fg: #000000;
                        --bg-alt: #f5f5f5;
                        --border: #ccc;
                    }
                    body {
                        font-family: Arial, sans-serif;
                        background-color: var(--bg);
                        color: var(--fg);
                        display: flex;
                        flex-direction: column;
                        align-items: center;
                        justify-content: center;
                        min-height: 100vh;
                        padding: 20px;
                        text-align: center;
                    }
                    form {
                        display: flex;
                        flex-direction: column;
                        gap: 12px;
                        padding: 20px;
                        background-color: var(--bg-alt);
                        border: 1px solid var(--border);
                        border-radius: 8px;
                    }
                    input[type="file"] {
                        color: var(--fg);
                    }
                    input[type="submit"] {
                        padding: 8px 16px;
                        background-color: var(--bg-alt);
                        color: var(--fg);
                        border: 1px solid var(--border);
                        border-radius: 4px;
                        cursor: pointer;
                    }
                    input[type="submit"]:hover {
                        background-color: var(--bg);
                    }
                </style>
            </head>
            <body>
                <h1>KaiserLift</h1>
                <form action="/upload" method="post" enctype="multipart/form-data">
                    <input type="file" name="file" />
                    <input type="submit" value="Upload" />
                </form>
                <div id="result"></div>
            </body>
        </html>
        """,
    )


@app.post("/upload", response_class=HTMLResponse)
async def upload(file: UploadFile = File(...)) -> str:
    """Process the uploaded CSV via the core pipeline and return HTML.

    All numerical computations occur within :func:`pipeline`. Any JavaScript
    embedded in the resulting HTML is dedicated solely to updating the user
    interface and performs no calculations.
    """

    # ``pipeline`` no longer embeds required JavaScript and CSS assets by
    # default.  Explicitly enable ``embed_assets`` so the returned HTML is a
    # standalone page suitable for direct rendering by the browser.
    return pipeline([file.file], embed_assets=True)


def main() -> None:
    """Start a Uvicorn development server."""

    import uvicorn

    port = int(os.getenv("PORT", 8000))
    uvicorn.run("kaiserlift.webapp:app", host="0.0.0.0", port=port, reload=False)


if __name__ == "__main__":  # pragma: no cover - manual server start
    main()
