"""
Soleprint - Bare-metal single-port development server.

Serves everything on a single port for basic testing without docker/nginx.
Routes /artery/*, /atlas/*, /station/* internally instead of redirecting.

Usage:
    python run.py              # Serves on :12000 with all subsystems
    PORT=8080 python run.py    # Custom port

This is for soleprint development only, not for managed rooms (use docker for those).
"""

import os
import sys
from pathlib import Path

# Add parent directory to path for imports
sys.path.insert(0, str(Path(__file__).parent.parent))

from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates

app = FastAPI(title="Soleprint (dev)", version="0.1.0")

templates = Jinja2Templates(directory=Path(__file__).parent)

# Base path for systems
SPR_ROOT = Path(__file__).parent.parent


def scan_directory(base_path: Path, pattern: str = "*") -> list[dict]:
    """Scan a directory and return list of items with metadata."""
    items = []
    if base_path.exists():
        for item in sorted(base_path.iterdir()):
            if item.is_dir() and not item.name.startswith(("_", ".")):
                readme = item / "README.md"
                description = ""
                if readme.exists():
                    # Get first non-empty, non-header line
                    for line in readme.read_text().split("\n"):
                        line = line.strip()
                        if line and not line.startswith("#"):
                            description = line[:100]
                            break
                items.append(
                    {
                        "name": item.name,
                        "path": str(item.relative_to(SPR_ROOT)),
                        "description": description,
                    }
                )
    return items


@app.get("/health")
def health():
    return {
        "status": "ok",
        "service": "soleprint-dev",
        "mode": "bare-metal",
    }


# === Artery ===


@app.get("/artery")
def artery_index():
    """List installed veins."""
    veins_path = SPR_ROOT / "artery" / "veins"
    veins = scan_directory(veins_path)
    return {
        "system": "artery",
        "tagline": "Todo lo vital",
        "veins": veins,
    }


@app.get("/artery/{path:path}")
def artery_route(path: str):
    """Artery sub-routes."""
    return {"system": "artery", "path": path, "message": "Artery route placeholder"}


# === Atlas ===


@app.get("/atlas")
def atlas_index():
    """List installed templates."""
    templates_path = SPR_ROOT / "atlas" / "templates"
    tpls = scan_directory(templates_path)
    return {
        "system": "atlas",
        "tagline": "Documentacion accionable",
        "templates": tpls,
    }


@app.get("/atlas/{path:path}")
def atlas_route(path: str):
    """Atlas sub-routes."""
    return {"system": "atlas", "path": path, "message": "Atlas route placeholder"}


# === Station ===


@app.get("/station")
def station_index():
    """List installed tools."""
    tools_path = SPR_ROOT / "station" / "tools"
    tools = scan_directory(tools_path)
    return {
        "system": "station",
        "tagline": "Monitores, Entornos y Herramientas",
        "tools": tools,
    }


@app.get("/station/{path:path}")
def station_route(path: str):
    """Station sub-routes."""
    return {"system": "station", "path": path, "message": "Station route placeholder"}


# === Main ===


@app.get("/")
def index(request: Request):
    """Landing page with links to subsystems."""
    return templates.TemplateResponse(
        "index.html",
        {
            "request": request,
            # In bare-metal mode, all routes are internal
            "artery": "/artery",
            "atlas": "/atlas",
            "station": "/station",
        },
    )


if __name__ == "__main__":
    import uvicorn

    port = int(os.getenv("PORT", "12000"))
    print(f"Soleprint bare-metal dev server starting on http://localhost:{port}")
    print("  /artery  - Connectors (veins)")
    print("  /atlas   - Documentation (templates)")
    print("  /station - Tools")
    print()

    uvicorn.run(
        "run:app",
        host="0.0.0.0",
        port=port,
        reload=True,
    )
