"""
PlantPlan FastAPI Backend
- Symbolbibliothek ausliefern
- Koordinaten normalisieren
- JSON/SVG Export
"""

import json
from pathlib import Path
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel

app = FastAPI(title="PlantPlan API")

# CORS: Erlaubt Zugriff vom lokalen Frontend Dev-Server
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:5173"],
    allow_methods=["*"],
    allow_headers=["*"],
)

CATALOG_DIR = Path(__file__).parent / "catalog"


# --- Models ---

class SketchPayload(BaseModel):
    shapes: list[dict]
    grid_size: int = 10


# --- Endpoints ---

@app.get("/symbols")
async def get_symbols():
    """Symbolbibliothek als JSON ausliefern."""
    catalog_file = CATALOG_DIR / "symbols.json"
    with open(catalog_file, encoding="utf-8") as f:
        return json.load(f)


@app.post("/normalize")
async def normalize(payload: SketchPayload):
    """Koordinaten auf Grid snappen und SVG-Pfade normalisieren."""
    cleaned = []
    for shape in payload.shapes:
        s = dict(shape)
        if "x" in s:
            s["x"] = round(s["x"] / payload.grid_size) * payload.grid_size
        if "y" in s:
            s["y"] = round(s["y"] / payload.grid_size) * payload.grid_size
        cleaned.append(s)
    return {"shapes": cleaned}


@app.post("/export")
async def export_sketch(payload: SketchPayload):
    """Finales Projektfile als JSON exportieren."""
    return {
        "json": {
            "version": "1.0",
            "shapes": payload.shapes,
        }
    }
