"""
Adds two more artifacts on top of the Oil & Gas GRC domain build-out
(scripts/seed_oil_gas_grc.py) for tenant d6dac324-d5dc-48b0-aef6-bf5be837e3c2:

1. A Page, "Master Data Management" — every one of the 26 Masters seeded
   earlier, grouped into 5 tabs (Reference & Configuration / GRC Core /
   Risk & Evidence / Assets / Commercial), each rendered as a full-CRUD
   data_list block (allow_create/edit/delete) so every entity can be
   browsed and managed from one page instead of the generic per-Master
   /masters/:id screen.
2. A Dashboard, "Oil & Gas GRC Analytics" — one KPI card per Master (26,
   record count) plus 9 status/type breakdown charts across the entities
   that carry a single_select or boolean field suitable for grouping
   (reference fields are stored as raw ids, not display values, at the
   dataset-query layer — see app/crud/dataset_query.py's
   resolve_grouped_series — so they're deliberately not used as chart
   x_field/slice_field here; that would produce raw-UUID axis labels).

Standalone script (same pattern as seed_oil_gas_grc.py): looks up the 26
Masters already seeded by name, inserts the Page/Dashboard/Widgets directly
through AsyncSessionLocal.

Idempotency: looked up by tenant_id + Page name "Master Data Management"
first; if found, exits without creating anything.

Usage:
    backend/.venv/Scripts/python.exe backend/scripts/seed_oil_gas_management_dashboard.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.identity import Tenant, User  # noqa: E402
from app.models.master import Master  # noqa: E402
from app.models.navigation import Dashboard, Page, Widget  # noqa: E402

TENANT_ID = uuid.UUID("d6dac324-d5dc-48b0-aef6-bf5be837e3c2")
PAGE_NAME = "Master Data Management"
DASHBOARD_NAME = "Oil & Gas GRC Analytics"

CANVAS_WIDTH = 1400
GAP = 20

COLORS = [
    "#2563eb", "#059669", "#d97706", "#7c3aed", "#dc2626", "#0891b2",
    "#db2777", "#65a30d", "#4f46e5", "#ea580c",
]

# Master name -> tab group label, in the same 5-category grouping used by
# the approved plan.
MASTER_GROUPS: list[tuple[str, list[str]]] = [
    ("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"]),
]

# (Master name, x_field, chart type, title) for the KPI-adjacent charts —
# every field here is single_select or boolean, never a reference field.
CHARTS: list[tuple[str, str, str, str]] = [
    ("Control", "status", "bar_chart", "Controls by Status"),
    ("Framework", "type", "pie_chart", "Frameworks by Type"),
    ("Framework", "status", "bar_chart", "Frameworks by Status"),
    ("Framework Version", "status", "bar_chart", "Framework Versions by Status"),
    ("Industry", "status", "pie_chart", "Industries by Status"),
    ("Risk Category", "status", "bar_chart", "Risk Categories by Status"),
    ("Asset Type", "status", "bar_chart", "Asset Types by Status"),
    ("Package", "status", "pie_chart", "Packages by Status"),
    ("Control Point", "required", "bar_chart", "Control Points by Required"),
]


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, x: int, y: int, w: int, h: int) -> dict:
    return {
        "id": uid(), "type": "data_list", "data_source": f"master:{master_id}",
        "live_pagination": True, "page_size": 10,
        "allow_create": True, "allow_edit": True, "allow_delete": True,
        "layout": {"x": x, "y": y, "w": w, "h": h},
    }


def tab_children(master_names: list[str], master_ids: dict[str, uuid.UUID], w: int = 660, h: int = 340) -> list[dict]:
    """Two-column stacked layout of caption + full-CRUD grid per Master,
    inside one tab group's own free-form canvas (its own local 0,0 origin)."""
    blocks = []
    for i, name in enumerate(master_names):
        col = i % 2
        row = i // 2
        x = col * (w + GAP)
        y = row * (h + 40 + GAP)
        blocks.append(text_block(name, x, y, w, 28, style="subheading"))
        blocks.append(grid_block(master_ids[name], x, y + 32, w, h))
    return blocks


async def main() -> None:
    async with AsyncSessionLocal() as db:
        tenant = await db.get(Tenant, TENANT_ID)
        if tenant is None:
            raise SystemExit(f"tenant {TENANT_ID} not found")

        existing = (
            await db.execute(select(Page).where(Page.tenant_id == TENANT_ID, Page.name == PAGE_NAME))
        ).scalar_one_or_none()
        if existing is not None:
            print(f"'{PAGE_NAME}' already exists (pages.id={existing.id}) — nothing to do.")
            return

        admin: User | None = (
            await db.execute(select(User).where(User.tenant_id == TENANT_ID).order_by(User.created_at).limit(1))
        ).scalar_one_or_none()
        admin_id = admin.id if admin else None

        masters = (await db.execute(select(Master).where(Master.tenant_id == TENANT_ID))).scalars().all()
        master_ids = {m.name: m.id for m in masters}
        missing = [n for _, names in MASTER_GROUPS for n in names if n not in master_ids]
        if missing:
            raise SystemExit(f"Missing Masters — run seed_oil_gas_grc.py first: {missing}")

        # ------------------------------------------------------------------
        # Page — "Master Data Management"
        # ------------------------------------------------------------------

        groups = []
        for label, names in MASTER_GROUPS:
            groups.append({"id": uid(), "label": label, "children": tab_children(names, master_ids)})

        tabs_block = {
            "id": uid(), "type": "tabs", "groups": groups,
            "layout": {"x": 0, "y": 56, "w": CANVAS_WIDTH, "h": 1200},
        }
        page_blocks = [text_block(PAGE_NAME, 0, 0, CANVAS_WIDTH, 40, style="heading"), tabs_block]

        page = Page(
            tenant_id=TENANT_ID, name=PAGE_NAME, blocks=page_blocks,
            canvas_width=CANVAS_WIDTH, status="published", created_by=admin_id,
        )
        db.add(page)

        # ------------------------------------------------------------------
        # Dashboard — "Oil & Gas GRC Analytics"
        # ------------------------------------------------------------------

        dashboard = Dashboard(tenant_id=TENANT_ID, name=DASHBOARD_NAME, status="published", created_by=admin_id)
        db.add(dashboard)
        await db.flush()

        sort_order = 0
        all_master_names = [n for _, names in MASTER_GROUPS for n in names]
        for i, name in enumerate(all_master_names):
            db.add(Widget(
                tenant_id=TENANT_ID, dashboard_id=dashboard.id, type="kpi_card",
                data_source=f"master:{master_ids[name]}", size="small", color=COLORS[i % len(COLORS)],
                refresh_interval="hourly", sort_order=sort_order, config={"title": name},
            ))
            sort_order += 1

        for master_name, x_field, chart_type, title in CHARTS:
            db.add(Widget(
                tenant_id=TENANT_ID, dashboard_id=dashboard.id, type=chart_type,
                data_source=f"master:{master_ids[master_name]}", size="medium", color=COLORS[sort_order % len(COLORS)],
                refresh_interval="hourly", sort_order=sort_order,
                config=({"title": title, "slice_field": x_field} if chart_type == "pie_chart" else {"title": title, "x_field": x_field}),
            ))
            sort_order += 1

        await db.commit()
        print(f"Created Page '{PAGE_NAME}' with {len(all_master_names)} full-CRUD Master grids across {len(MASTER_GROUPS)} tabs.")
        print(f"Created Dashboard '{DASHBOARD_NAME}' with {len(all_master_names)} KPI cards and {len(CHARTS)} charts.")


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