"""Sprint 6E.3 regeneration-profile contracts using synthetic data only."""

from __future__ import annotations

import importlib
import importlib.util
import json
import os
import subprocess
import sys
from datetime import date
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
WORKER = ROOT / "scripts/health/health_dashboard_action_worker.py"
GENERATOR = ROOT / "scripts/health/health_dashboard_v5.py"
sys.path.insert(0, str(ROOT / "tests"))
build_dashboard_v5_fixture = importlib.import_module(
    "fixtures.dashboard_v5_fixture"
).build_dashboard_v5_fixture

PROFILE_ASSETS = (
    "dashboard-v5-api-explorer.js",
    "dashboard-v5-day-controller.js",
    "dashboard-v5-record.js",
)


def load_worker(name: str):
    spec = importlib.util.spec_from_file_location(name, WORKER)
    assert spec and spec.loader
    module = importlib.util.module_from_spec(spec)
    sys.modules[name] = module
    spec.loader.exec_module(module)
    return module


def generate(database: Path, output: Path, *, profiled: bool) -> str:
    command = [
        sys.executable,
        str(GENERATOR),
        "--db",
        str(database),
        "--output",
        str(output),
        "--today",
        "2026-07-15",
    ]
    if profiled:
        command.append("--health-record-6e")
    subprocess.run(command, check=True, timeout=120, capture_output=True, text=True)
    return output.read_text(encoding="utf-8")


def test_default_and_health_record_profiles_generate_exact_assets(tmp_path):
    database = tmp_path / "synthetic.db"
    build_dashboard_v5_fixture(database)
    standard = generate(database, tmp_path / "standard.html", profiled=False)
    preview = generate(database, tmp_path / "preview.html", profiled=True)
    assert all(asset not in standard for asset in PROFILE_ASSETS)
    assert all(asset in preview for asset in PROFILE_ASSETS)
    assert "data-record-tab" not in standard
    assert "data-record-tab" in preview


def test_worker_profile_command_and_queue_regeneration_preserve_preview(
    tmp_path, monkeypatch
):
    monkeypatch.setenv("HEALTH_DASHBOARD_V5_PROFILE", "health-record-6e")
    module = load_worker("health_dashboard_action_worker_sprint6e3_preview")
    database = tmp_path / "synthetic.db"
    build_dashboard_v5_fixture(database)
    inbox = tmp_path / "actions"
    inbox.mkdir(mode=0o700)
    output = tmp_path / "preview.html"
    monkeypatch.setattr(module, "DASHBOARD_DB", database)
    monkeypatch.setattr(module, "ACTION_INBOX", inbox)
    monkeypatch.setattr(module, "DASHBOARD_V5_FILE", output)
    monkeypatch.setattr(module, "DASHBOARD_V5_PROFILE", "health-record-6e")

    action = inbox / ("a" * 32 + ".json")
    action.write_text(
        json.dumps(
            {
                "version": 1,
                "action": "symptom_checkin",
                "date": date.today().isoformat(),
                "scores": {field: 0 for field in module.FIELDS},
                "notes": "synthetic queue profile regression",
            }
        ),
        encoding="utf-8",
    )
    action.chmod(0o600)
    assert module.main() == 0
    assert not action.exists()
    html = output.read_text(encoding="utf-8")
    assert all(asset in html for asset in PROFILE_ASSETS)
    assert "data-record-tab" in html


def test_default_worker_command_omits_profile_flag(tmp_path, monkeypatch):
    monkeypatch.delenv("HEALTH_DASHBOARD_V5_PROFILE", raising=False)
    module = load_worker("health_dashboard_action_worker_sprint6e3_default")
    database = tmp_path / "synthetic.db"
    monkeypatch.setattr(module, "DASHBOARD_DB", database)
    monkeypatch.setattr(module, "DASHBOARD_V5_FILE", tmp_path / "v5.html")
    commands: list[list[str]] = []
    monkeypatch.setattr(
        module.subprocess, "run", lambda command, **_kwargs: commands.append(command)
    )
    module.apply_action(
        date.today().isoformat(), {field: 0 for field in module.FIELDS}, ""
    )
    assert "--health-record-6e" not in commands[-1]


def test_versioned_worker_unit_pins_the_authorized_preview_profile():
    unit = (ROOT / "deploy/systemd/health-dashboard-action-worker.service").read_text(
        encoding="utf-8"
    )
    assert "Environment=HEALTH_DASHBOARD_V5_PROFILE=health-record-6e" in unit


def test_invalid_or_conflicting_profile_fails_before_runtime_touch(tmp_path):
    for invalid in ("unknown", "default,health-record-6e", " health-record-6e"):
        inbox = tmp_path / invalid.replace("/", "_").replace(",", "_")
        environment = os.environ.copy()
        environment.update(
            {
                "HEALTH_DASHBOARD_V5_PROFILE": invalid,
                "HEALTH_DASHBOARD_DB": str(tmp_path / "must-not-change.db"),
                "HEALTH_DASHBOARD_ACTION_INBOX": str(inbox),
            }
        )
        result = subprocess.run(
            [sys.executable, str(WORKER)],
            env=environment,
            timeout=30,
            capture_output=True,
            text=True,
        )
        assert result.returncode != 0
        assert "invalid HEALTH_DASHBOARD_V5_PROFILE" in result.stderr
        assert not inbox.exists()
