from fastapi import APIRouter

from app.db import fetch_view
from app.schemas.site import SiteSettings

router = APIRouter(prefix="/api", tags=["site"])


@router.get("/site-settings", response_model=SiteSettings)
def get_site_settings() -> dict:
    settings_row = fetch_view("vw_site_settings")[0]
    nav_rows = fetch_view("vw_nav_items", "location = :loc", {"loc": "header"})
    footer_rows = fetch_view("vw_footer_columns")

    # Nest header children under their parent
    tops = [r for r in nav_rows if r["parentId"] is None]
    primary_nav = []
    for top in tops:
        children = [
            {"label": c["label"], "href": c["href"]}
            for c in nav_rows if c["parentId"] == top["id"]
        ]
        item = {"label": top["label"], "href": top["href"]}
        if children:
            item["children"] = children
        primary_nav.append(item)

    # Group footer rows into columns
    columns: dict[str, dict] = {}
    for row in footer_rows:
        col = columns.setdefault(
            row["columnTitle"], {"title": row["columnTitle"], "links": []}
        )
        col["links"].append({"label": row["linkLabel"], "href": row["linkHref"]})

    return {
        **settings_row,
        "primaryNav": primary_nav,
        "footerColumns": list(columns.values()),
    }
