"""可重复执行的演示数据。"""
from __future__ import annotations

import hashlib
import json

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from .enums import DutStatus, HostStatus, PowerState
from .models import Dut, FirmwareArtifact, OobController, TestHost, Workflow, utcnow


def _spec_hash(spec: dict) -> str:
    raw = json.dumps(spec, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(raw.encode("utf-8")).hexdigest()


async def ensure_seed_data(session: AsyncSession) -> None:
    existing = await session.scalar(select(Workflow.id).limit(1))
    if existing:
        return

    oob = OobController(
        name="OOB-05",
        kind="simulated",
        endpoint="sim://oob-05",
        capabilities={"power": True, "reset": True, "atx": True, "ac": True, "hdmi": True},
        status=HostStatus.ONLINE.value,
        power_state=PowerState.ON.value,
        last_seen_at=utcnow(),
        temperature_c=42.6,
    )
    session.add(oob)
    await session.flush()

    host = TestHost(
        name="WS-05",
        os_family="linux",
        os_version="Ubuntu 22.04.4 LTS",
        kernel="6.8.0-40-generic",
        cpu="Intel Core i7-13700",
        motherboard="FlashOps SIM-X1",
        bios_version="F26b",
        agent_version="0.1.0-sim",
        ip_address="192.0.2.15",
        status=HostStatus.ONLINE.value,
        last_heartbeat_at=utcnow(),
        oob_controller_id=oob.id,
        toolchain={"fio": "3.36", "nvme-cli": "2.9.1"},
        labels={"system_device_paths": ["/dev/nvme0n1"]},
    )
    session.add(host)
    await session.flush()

    dut = Dut(
        serial="S6XNNA0T609",
        model="NV-E1T92",
        vendor="Lab Sample",
        capacity_gb=1920,
        form_factor="U.2",
        current_firmware="3.2.1",
        bdf="0000:03:00.0",
        device_path="/dev/nvme1n1",
        test_host_id=host.id,
        status=DutStatus.IDLE.value,
        allow_destructive=True,
        health={"temperature_c": 43, "percentage_used": 12, "critical_warning": 0},
        labels={"purpose": "test-only"},
    )
    session.add(dut)

    firmware_a = FirmwareArtifact(
        version="3.2.1",
        label="A / 基线",
        sha256="4bd1" + "0" * 56 + "08ce",
        signature="simulated-valid-signature",
        applicable_models=[dut.model],
        file_uri="sim://firmware/FW_3.2.1.bin",
        uploaded_by="seed",
    )
    firmware_b = FirmwareArtifact(
        version="3.3.0-rc3",
        label="B / 候选",
        sha256="9f2c" + "0" * 56 + "41aa",
        signature="simulated-valid-signature",
        applicable_models=[dut.model],
        file_uri="sim://firmware/FW_3.3.0-rc3.bin",
        uploaded_by="seed",
    )
    session.add_all([firmware_a, firmware_b])

    spec = {
        "key": "fw-ab-regression",
        "name": "固件 A/B 电源状态回归",
        "version": 3,
        "danger_level": "high",
        "params": {"loops": {"type": "int", "default": 8, "min": 1, "max": 10000}},
        "steps": [
            {"key": "preflight", "type": "precheck", "adapter": "safety"},
            {
                "key": "flash-fw-b",
                "type": "command",
                "adapter": "nvme_cli",
                "template": "nvme_fw_download_commit",
                "danger": "high",
                "idempotent": False,
                "checkpoint": True,
            },
            {
                "key": "regression-loop",
                "type": "loop",
                "body": [
                    {
                        "key": "workload",
                        "type": "command",
                        "adapter": "fio",
                        "idempotent": True,
                        "retry": 1,
                    },
                    {"key": "enumeration-check", "type": "device_check", "adapter": "nvme_cli"},
                    {"key": "integrity-check", "type": "command", "adapter": "shell"},
                ],
                "checkpoint": True,
            },
            {"key": "report", "type": "report", "adapter": "builtin"},
        ],
    }
    workflow = Workflow(
        key=spec["key"],
        name=spec["name"],
        version=spec["version"],
        spec=spec,
        spec_hash=_spec_hash(spec),
        danger_level="high",
        source_sop="内置模拟 SOP v1",
        published=True,
        approved_by="system-seed",
    )
    session.add(workflow)
    await session.flush()
