"""
Fixes a layout bug in the 4 Oil & Gas GRC Pages seeded by seed_oil_gas_grc.py
and seed_oil_gas_management_dashboard.py: every stacked data_list grid was
given a box height (340-360px) far shorter than what a 10-row grid with its
own search bar, Add button, and pagination footer actually renders at
(500px+, more with wrapping description columns). The free-form canvas
doesn't clip a block's overflow, so the next row's blocks were absolutely
positioned assuming the too-small box and ended up drawn on top of the
previous row's still-visible content — invisible in the Designer's own
in-flow canvas view, but visible as overlapping tables once the Public
Portal's PageRunner renders the page at its real free-form coordinates.

Rebuilds each affected Page's `blocks` JSON with a much taller per-grid box
(700px) and re-derives every row's y-offset from that, then UPDATEs the
existing Page rows in place (same ids — nothing else about them changes).

Usage:
    backend/.venv/Scripts/python.exe backend/scripts/fix_oil_gas_page_heights.py
"""

import asyncio
import sys
import uuid
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from sqlalchemy import select  # noqa: E402

from app.core.database import AsyncSessionLocal  # noqa: E402
from app.models.master import Master  # noqa: E402
from app.models.navigation import Page  # noqa: E402

TENANT_ID = uuid.UUID("d6dac324-d5dc-48b0-aef6-bf5be837e3c2")
CANVAS_WIDTH = 1400
GAP = 20
GRID_W = 660
GRID_H = 700  # was 340-360 — the actual fix


def uid() -> str:
    return str(uuid.uuid4())


def text_block(text: str, x: int, y: int, w: int, h: int, style: str = "heading") -> dict:
    return {"id": uid(), "type": "text", "text": text, "text_style": style, "layout": {"x": x, "y": y, "w": w, "h": h}}


def grid_block(master_id: uuid.UUID, columns: list[str] | None, x: int, y: int, w: int, h: int, crud: bool) -> dict:
    b = {
        "id": uid(), "type": "data_list", "data_source": f"master:{master_id}",
        "live_pagination": True, "page_size": 10,
        "layout": {"x": x, "y": y, "w": w, "h": h},
    }
    if columns is not None:
        b["columns"] = columns
    if crud:
        b["allow_create"] = True
        b["allow_edit"] = True
        b["allow_delete"] = True
    return b


def flow_grids(entries: list[tuple], start_y: int, crud: bool = False, w: int = GRID_W, h: int = GRID_H) -> tuple[list[dict], int]:
    """entries: (master_key_or_id, columns, caption). Two-column stacked flow."""
    blocks = []
    y = start_y
    for i, (key, cols, caption) in enumerate(entries):
        col = i % 2
        row = i // 2
        x = col * (w + GAP)
        row_y = y + row * (h + 40 + GAP)
        blocks.append(text_block(caption, x, row_y, w, 28, style="subheading"))
        blocks.append(grid_block(key, cols, x, row_y + 32, w, h, crud))
    rows_used = (len(entries) + 1) // 2
    total_h = y + rows_used * (h + 40 + GAP)
    return blocks, total_h


async def main() -> None:
    async with AsyncSessionLocal() as db:
        masters = (await db.execute(select(Master).where(Master.tenant_id == TENANT_ID))).scalars().all()
        mid = {m.name: m.id for m in masters}

        def get(name: str) -> uuid.UUID:
            return mid[name]

        # ------------------------------------------------------------------
        # Oil & Gas GRC Command Center
        # ------------------------------------------------------------------
        page1 = (await db.execute(select(Page).where(Page.tenant_id == TENANT_ID, Page.name == "Oil & Gas GRC Command Center"))).scalar_one_or_none()
        if page1:
            kpi_specs = [("Framework", "Frameworks", "#2563eb"), ("Control", "Controls", "#059669"), ("Risk Category", "Risk Categories", "#d97706"), ("Asset Type", "Asset Types", "#7c3aed")]
            kpi_w = (CANVAS_WIDTH - 3 * GAP) // 4
            blocks = [text_block("Oil & Gas GRC Command Center", 0, 0, CANVAS_WIDTH, 40, style="heading")]
            for i, (mkey, caption, color) in enumerate(kpi_specs):
                x = i * (kpi_w + GAP)
                blocks.append(text_block(caption, x, 56, kpi_w, 24, style="subheading"))
                blocks.append({"id": uid(), "type": "kpi_card", "data_source": f"master:{get(mkey)}", "color": color, "layout": {"x": x, "y": 84, "w": kpi_w, "h": 100}})
            grid_blocks, _ = flow_grids([
                (get("Framework"), ["code", "name", "type", "status"], "Frameworks"),
                (get("Control"), ["code", "title", "category", "status"], "Controls"),
                (get("Risk Category"), ["code", "name", "industry", "status"], "Risk Categories"),
                (get("Asset Type"), ["code", "name", "status"], "Asset Types"),
            ], start_y=204)
            blocks += grid_blocks
            page1.blocks = blocks
            print(f"Updated 'Oil & Gas GRC Command Center' ({page1.id})")

        # ------------------------------------------------------------------
        # Compliance Framework Explorer
        # ------------------------------------------------------------------
        page2 = (await db.execute(select(Page).where(Page.tenant_id == TENANT_ID, Page.name == "Compliance Framework Explorer"))).scalar_one_or_none()
        if page2:
            blocks = [text_block("Compliance Framework Explorer", 0, 0, CANVAS_WIDTH, 40, style="heading")]
            g1, next_y = flow_grids([
                (get("Framework"), ["code", "name", "type", "status"], "Frameworks"),
                (get("Framework Version"), ["version", "framework", "status"], "Framework Versions"),
            ], start_y=56)
            blocks += g1
            g2, next_y2 = flow_grids([
                (get("Clause"), ["clause_number", "title", "framework_version", "status"], "Clauses / Domains"),
                (get("Objective"), ["code", "title", "clause", "status"], "Objectives"),
            ], start_y=next_y)
            blocks += g2
            g3, _ = flow_grids([
                (get("Control Point"), ["code", "title", "result_type", "status"], "Control Points"),
            ], start_y=next_y2)
            blocks += g3
            page2.blocks = blocks
            print(f"Updated 'Compliance Framework Explorer' ({page2.id})")

        # ------------------------------------------------------------------
        # Asset & Unit Register
        # ------------------------------------------------------------------
        page3 = (await db.execute(select(Page).where(Page.tenant_id == TENANT_ID, Page.name == "Asset & Unit Register"))).scalar_one_or_none()
        if page3:
            blocks = [text_block("Asset & Unit Register", 0, 0, CANVAS_WIDTH, 40, style="heading")]
            g, _ = flow_grids([
                (get("Unit Type"), ["code", "name", "industry", "status"], "Unit Types"),
                (get("Section"), ["code", "name", "unit_type", "status"], "Sections"),
                (get("Asset Type"), ["code", "name", "status"], "Asset Types"),
                (get("Asset Category"), ["code", "name", "industry", "status"], "Asset Categories"),
            ], start_y=56)
            blocks += g
            page3.blocks = blocks
            print(f"Updated 'Asset & Unit Register' ({page3.id})")

        # ------------------------------------------------------------------
        # Master Data Management (tabs of full-CRUD grids, every column shown)
        # ------------------------------------------------------------------
        page4 = (await db.execute(select(Page).where(Page.tenant_id == TENANT_ID, Page.name == "Master Data Management"))).scalar_one_or_none()
        if page4:
            groups_spec = [
                ("Reference & Configuration", ["Currency", "Sector", "Timezone", "Country", "Industry", "Unit Type", "Section"]),
                ("GRC Core", ["Control Category", "Control Type", "Result Type", "Control", "Control Point", "Framework", "Framework Version", "Clause", "Objective"]),
                ("Risk & Evidence", ["Risk Category", "Evidence Type"]),
                ("Assets", ["Asset Type", "Asset Category", "Asset Category Relation", "Asset Type-Category Mapping"]),
                ("Commercial", ["Package", "Module", "Feature", "Package Assignment"]),
            ]
            groups = []
            for label, names in groups_spec:
                entries = [(get(n), None, n) for n in names]
                children, _ = flow_grids(entries, start_y=0, crud=True)
                groups.append({"id": uid(), "label": label, "children": children})
            tabs_block = {"id": uid(), "type": "tabs", "groups": groups, "layout": {"x": 0, "y": 56, "w": CANVAS_WIDTH, "h": 2400}}
            page4.blocks = [text_block("Master Data Management", 0, 0, CANVAS_WIDTH, 40, style="heading"), tabs_block]
            print(f"Updated 'Master Data Management' ({page4.id})")

        await db.commit()
        print("Done.")


if __name__ == "__main__":
    asyncio.run(main())
