"""
D1 — Diagnostics dashboard.

A "is this device OK?" console, consumer-first. Reproduces the Claude
Design handoff (D1-diagnostics.html):

  status bar : back chevron + "Diagnostics" · battery · clock
  hero       : check-circle glyph + device line + "match confidence" meter
  grid       : 2×2 detail cards (Hardware / System / Storage / Recognized),
               each a key/value list in consumer language
  CTA        : focused "Create a support report" strip → support screen
  footer     : A make report · X show technical details · B back

X toggles an advanced tier (kernel hash / dtb sha / sd partition table —
the geek view named in the spec). The DEFAULT consumer view is the one
the product owner cares about and is fully built; the advanced view swaps
the four cards' key/values for the technical equivalents.
"""

from __future__ import annotations

import pygame

from ..design import tokens as t
from ..shared import widgets as w
from ..shared import fonts, icons, render
from ..shared import backend

# ── layout (640×480 stage; body between status bar 48 and footer 448) ──
HERO_Y = 56
HERO_H = 60
GRID_TOP = HERO_Y + HERO_H + 10          # 126
SUPPORT_H = 56
SUPPORT_Y = 448 - 8 - SUPPORT_H          # 384
GRID_BOTTOM = SUPPORT_Y - 8              # 376
GRID_GAP = 8
CARD_W = (608 - GRID_GAP) // 2           # 300
CARD_H = (GRID_BOTTOM - GRID_TOP - GRID_GAP) // 2  # 117
COL_X = [16, 16 + CARD_W + GRID_GAP]
ROW_Y = [GRID_TOP, GRID_TOP + CARD_H + GRID_GAP]


class DiagnosticsScreen:
    name = "diagnostics"

    def __init__(self, app):
        self.app = app
        self.focus = 0          # only the support CTA is focusable here
        self.advanced = False   # X toggles the technical tier

        # hero
        self.hero_title = "R36S"
        self.hero_sub = ("All systems recognized · running", "dArkOS · March 2026")
        self.confidence = (4, 5)

        # four detail cards — consumer-first key/value rows.
        # rows = (key, value, value_state)  state ∈ {None,"ok","warn","cyan"}
        self.cards = [
            dict(title="Hardware", icon="ph-device-mobile",
                 icon_color=t.Color.ACCENT_CYAN, rows=[
                     ("device", "R36S", None),
                     ("memory", "4 GB", None),
                     ('display', '3.5" · working', "ok"),
                     ("audio jack", "working", "ok"),
                 ]),
            dict(title="System", icon="ph-broadcast",
                 icon_color=t.Color.ACCENT_ROSE, rows=[
                     ("firmware", "dArkOSRE", None),
                     ("version", "March 2026", "cyan"),
                     ("last reboot", "3 hours ago", None),
                     ("aahead", "1.4.0 · up to date", "ok"),
                 ]),
            dict(title="Storage", icon="ph-download-simple",
                 icon_color=t.Color.SUCCESS, rows=[
                     ("card 1", "64 GB · healthy", "ok"),
                     ("card 2", "32 GB · games", None),
                     ("filesystem", "exfat · clean", None),
                     ("free", "38 GB total", None),
                 ]),
            dict(title="Recognized for AAhead", icon="ph-warning",
                 icon_color=t.Color.ACCENT_PEACH, rows=[
                     ("bluetooth", "ready", "ok"),
                     ("wi-fi adapter", "works", "ok"),
                     ("rumble", "not checked yet", "warn"),
                     ("led strip", "not available", None),
                 ]),
        ]
        # advanced (geek) tier — only what the spec names; never invented.
        self.cards_adv = [
            dict(title="Hardware", icon="ph-device-mobile",
                 icon_color=t.Color.ACCENT_CYAN, rows=[
                     ("soc", "rk3326", None),
                     ("board rev", "v3", None),
                     ("panel id", "0x4854", None),
                     ("ram", "4096 MiB", None),
                 ]),
            dict(title="System", icon="ph-broadcast",
                 icon_color=t.Color.ACCENT_ROSE, rows=[
                     ("kernel", "4.4.189", None),
                     ("vermagic", "SMP aarch64", "cyan"),
                     ("dtb sha", "a3f1…9c2", None),
                     ("aahead", "1.4.0", "ok"),
                 ]),
            dict(title="Storage", icon="ph-download-simple",
                 icon_color=t.Color.SUCCESS, rows=[
                     ("mmcblk0", "64 GB", "ok"),
                     ("p1 boot", "256 MB vfat", None),
                     ("p2 roms", "exfat", None),
                     ("mmcblk1", "32 GB", None),
                 ]),
            dict(title="Recognized for AAhead", icon="ph-warning",
                 icon_color=t.Color.ACCENT_PEACH, rows=[
                     ("btusb", "0bda:b00c", "ok"),
                     ("wlan0", "rtl8723bs", "ok"),
                     ("rumble", "no evdev", "warn"),
                     ("leds", "not exposed", None),
                 ]),
        ]
        self._load_live_report()

    def _load_live_report(self):
        env = backend.diagnostics_report()
        if not env or not env.get("ok"):
            return
        data = env.get("data") or {}
        self.hero_title = data.get("device") or self.hero_title
        firmware = data.get("firmware") or "Unknown firmware"
        version = data.get("version") or "unknown"
        self.hero_sub = ("All systems recognized · running", f"{firmware} · {version}")
        confidence = data.get("confidence") or {}
        self.confidence = (
            int(confidence.get("filled") or self.confidence[0]),
            int(confidence.get("total") or self.confidence[1]),
        )

        storage_rows = []
        for item in data.get("storage") or []:
            slot = item.get("slot", "?")
            storage_rows.append((f"card {slot}", item.get("size", "unknown"), "ok" if item.get("status") == "healthy" else None))
        storage_fillers = [
            ("card 2", "not detected", None),
            ("filesystem", "not checked", None),
            ("free", "see card 1", None),
        ]
        while len(storage_rows) < 4 and storage_fillers:
            storage_rows.append(storage_fillers.pop(0))

        recognized = data.get("recognized") or {}
        self.cards = [
            dict(title="Hardware", icon="ph-device-mobile",
                 icon_color=t.Color.ACCENT_CYAN, rows=[
                     ("device", data.get("device", "unknown"), None),
                     ("memory", data.get("memory", "unknown"), None),
                     ("display", data.get("display", "not checked"), "ok"),
                     ("audio jack", data.get("audio_jack", "not checked"), None),
                 ]),
            dict(title="System", icon="ph-broadcast",
                 icon_color=t.Color.ACCENT_ROSE, rows=[
                     ("firmware", firmware, None),
                     ("version", version, "cyan"),
                     ("last reboot", data.get("last_reboot", "unknown"), None),
                     ("aahead", data.get("aahead", "development"), "ok"),
                 ]),
            dict(title="Storage", icon="ph-download-simple",
                 icon_color=t.Color.SUCCESS, rows=storage_rows[:4]),
            dict(title="Recognized for AAhead", icon="ph-warning",
                 icon_color=t.Color.ACCENT_PEACH, rows=[
                     ("bluetooth", recognized.get("bluetooth", "not checked"), None),
                     ("wi-fi adapter", recognized.get("wifi_adapter", "not detected"), None),
                     ("rumble", recognized.get("rumble", "not checked"), "warn"),
                     ("led strip", recognized.get("led_strip", "not available"), None),
                 ]),
        ]

        technical = data.get("technical") or {}
        detector = technical.get("detector") or {}
        self.cards_adv = [
            dict(title="Hardware", icon="ph-device-mobile",
                 icon_color=t.Color.ACCENT_CYAN, rows=[
                     ("raw model", str(technical.get("raw_model") or data.get("device") or "unknown")[:20], None),
                     ("kernel", str(technical.get("kernel") or "unknown")[:20], None),
                     ("rootfs", str(technical.get("rootfs") or "unknown")[:20], None),
                     ("csr clone", str(technical.get("csr_clone_present") or "unknown")[:20], None),
                 ]),
            dict(title="System", icon="ph-broadcast",
                 icon_color=t.Color.ACCENT_ROSE, rows=[
                     ("boot", str(technical.get("boot_scheme") or "unknown")[:20], None),
                     ("image sha", str(technical.get("boot_image_sha256") or "unknown")[:20], "cyan"),
                     ("btusb", str(technical.get("btusb_vermagic") or "not found")[:20], None),
                     ("aahead", data.get("aahead", "development"), "ok"),
                 ]),
            dict(title="Storage", icon="ph-download-simple",
                 icon_color=t.Color.SUCCESS, rows=[
                     ("boot writable", detector.get("boot_writable", "unknown"), None),
                     ("modules rw", detector.get("lib_modules_writable", "unknown"), None),
                     ("btusb path", str(detector.get("btusb_path", "unknown"))[:20], None),
                     ("boot file", detector.get("boot_kernel_file", "unknown"), None),
                 ]),
            dict(title="Recognized for AAhead", icon="ph-warning",
                 icon_color=t.Color.ACCENT_PEACH, rows=[
                     ("bluetooth", recognized.get("bluetooth", "not checked"), None),
                     ("wifi", recognized.get("wifi_adapter", "not detected"), None),
                     ("confidence", f"{self.confidence[0]}/{self.confidence[1]}", "cyan"),
                     ("schema", env.get("schema", "unknown"), None),
                 ]),
        ]

    # ── input ─────────────────────────────────────────────────────────
    def on_action(self, action):
        if action == "a":
            from .support_report import SupportReportScreen
            self.app.push(SupportReportScreen(self.app))
        elif action == "x":
            self.advanced = not self.advanced
            self.app.toast("Technical details on" if self.advanced
                           else "Technical details off")
        elif action == "b":
            self.app.pop()

    def update(self, dt_ms):
        pass

    # ── draw ──────────────────────────────────────────────────────────
    def draw(self, surf):
        w.status_bar(surf, title="Diagnostics", back=True)
        self._draw_hero(surf)
        cards = self.cards_adv if self.advanced else self.cards
        for i, card in enumerate(cards):
            r, c = divmod(i, 2)
            rect = pygame.Rect(COL_X[c], ROW_Y[r], CARD_W, CARD_H)
            w.info_card(surf, rect, title=card["title"], icon_name=card["icon"],
                        icon_color=card["icon_color"], rows=card["rows"])
        self._draw_support(surf)
        w.footer_hints(surf, [("A", "make report"),
                              ("X", "details"), ("B", "back")])

    def _draw_hero(self, surf):
        # gradient rounded glyph (mint→cyan tint per HTML) with success check
        gbox = 48
        box = render.rounded_gradient(
            (gbox, gbox), t.with_alpha(t.Color.SUCCESS, 0.22)[:3],
            t.with_alpha(t.Color.ACCENT_CYAN, 0.18)[:3], 12, 135)
        # subtle success border + glyph
        pygame.draw.rect(box, t.with_alpha(t.Color.SUCCESS, 0.40),
                         (0, 0, gbox, gbox), width=1, border_radius=12)
        ic = icons.icon("ph-check-circle", 26, t.Color.SUCCESS)
        box.blit(ic, ((gbox - 26) // 2, (gbox - 26) // 2))
        surf.blit(box, (16, HERO_Y))

        tx = 16 + gbox + 14
        title = fonts.render(t.Type.TITLE, self.hero_title, t.Color.TEXT_PRIMARY)
        surf.blit(title, (tx, HERO_Y + 2))
        # subline: muted lead + primary bold firmware token
        sy = HERO_Y + 2 + title.get_height() + 4
        lead = fonts.render(t.Type.BODY_SM, self.hero_sub[0] + " ", t.Color.TEXT_SECONDARY)
        surf.blit(lead, (tx, sy))
        fw = fonts.render(t.Type.LABEL_SM, self.hero_sub[1], t.Color.TEXT_PRIMARY)
        surf.blit(fw, (tx + lead.get_width(), sy))

        # right side: "match confidence" label + meter + "high · n/m"
        filled, total = self.confidence
        meter = w.confidence_meter(filled, total)
        rx = 640 - 16
        lbl = fonts.render(t.Type.META_SM, "MATCH CONFIDENCE", t.Color.TEXT_MUTED)
        surf.blit(lbl, (rx - lbl.get_width(), HERO_Y + 2))
        surf.blit(meter, (rx - meter.get_width(), HERO_Y + 2 + lbl.get_height() + 4))
        verdict = fonts.render(t.Type.META_SM, f"high · {filled}/{total}", t.Color.SUCCESS)
        surf.blit(verdict, (rx - verdict.get_width(),
                            HERO_Y + 2 + lbl.get_height() + 4 + meter.get_height() + 4))

        pygame.draw.line(surf, t.Color.BORDER_SOFT,
                         (16, HERO_Y + HERO_H), (624, HERO_Y + HERO_H), 1)

    def _draw_support(self, surf):
        rect = pygame.Rect(16, SUPPORT_Y, 608, SUPPORT_H)
        focused = self.focus == 0
        # cyan-tinted base panel (matches .support background)
        body = pygame.Surface((rect.w, rect.h), pygame.SRCALPHA)
        pygame.draw.rect(body, t.with_alpha(t.Color.ACCENT_CYAN, 0.08),
                         (0, 0, rect.w, rect.h), border_radius=10)
        if not focused:
            pygame.draw.rect(body, t.with_alpha(t.Color.ACCENT_CYAN, 0.30),
                             (0, 0, rect.w, rect.h), width=1, border_radius=10)

        pad = 14
        # rose/cyan tinted icon chip
        ibox = 32
        chip = render.rounded_gradient(
            (ibox, ibox), t.with_alpha(t.Color.ACCENT_ROSE, 0.18)[:3],
            t.with_alpha(t.Color.ACCENT_CYAN, 0.18)[:3], 8, 135)
        fic = icons.icon("ph-file-text", 18, t.Color.ACCENT_ROSE)
        chip.blit(fic, ((ibox - 18) // 2, (ibox - 18) // 2))
        body.blit(chip, (pad, (rect.h - ibox) // 2))

        # CTA pill (right) — measured first so the meta can fill the middle
        cta_label = fonts.render(t.Type.BODY_SM, "Make report · A", t.Color.TEXT_PRIMARY)
        cta_ic = icons.icon("ph-download-simple", 13, t.Color.ACCENT_CYAN)
        cta_w = 12 + cta_ic.get_width() + 6 + cta_label.get_width() + 12
        cta_h = 32
        cta = render.rounded_fill((cta_w, cta_h), t.Color.SURFACE_ELEVATED, 999)
        pygame.draw.rect(cta, t.Color.BORDER_SOFT, (0, 0, cta_w, cta_h),
                         width=1, border_radius=999)
        cx = 12
        cta.blit(cta_ic, (cx, (cta_h - cta_ic.get_height()) // 2))
        cx += cta_ic.get_width() + 6
        cta.blit(cta_label, (cx, (cta_h - cta_label.get_height()) // 2))
        cta_x = rect.w - pad - cta_w
        body.blit(cta, (cta_x, (rect.h - cta_h) // 2))

        # meta: title + mono subline
        mx = pad + ibox + 12
        title = fonts.render(t.Type.LABEL_SM, "Create a support report", t.Color.TEXT_PRIMARY)
        sub = fonts.render(t.Type.META_SM,
                           "bundles this page + recent logs · /roms/aahead/reports",
                           t.Color.TEXT_MUTED)
        stack_h = title.get_height() + 2 + sub.get_height()
        my = (rect.h - stack_h) // 2
        body.blit(title, (mx, my))
        body.blit(sub, (mx, my + title.get_height() + 2))

        if focused:
            glow, gpos = render.focus_glow(rect, 10)
            surf.blit(glow, gpos)
            surf.blit(body, rect.topleft)
            surf.blit(render.gradient_border((rect.w, rect.h), 10), rect.topleft)
        else:
            surf.blit(body, rect.topleft)
