import json
import subprocess
from pathlib import Path

import pytest

ROOT = Path(__file__).resolve().parents[1]


def write_inv(tmpdir, image_path, checksum):
    inv = {
        "classes": [
            {
                "name": "test-class",
                "arch": "arm64",
                "os": "testos",
                "image": f"file://{image_path}",
                "checksum": checksum,
                "default_labels": {"role": "worker"},
            }
        ],
        "nodes": [
            {
                "name": "node-a",
                "class": "test-class",
                "hostname": "node-a",
                "ip": "10.0.0.10",
                "k3s_role": "agent",
            }
        ],
    }
    inv_path = Path(tmpdir) / "inv.yaml"
    inv_path.write_text(json.dumps(inv))
    return inv_path


def test_plan_output_contains_actions(tmp_path):
    dummy = tmp_path / "dummy.img"
    dummy.write_bytes(b"dummy")
    import hashlib

    checksum = "sha256:" + hashlib.sha256(dummy.read_bytes()).hexdigest()
    inv_path = write_inv(tmp_path, dummy, checksum)
    cache_dir = tmp_path / "cache"
    cmd = ["go", "run", "./cmd/metis", "plan", "--inventory", str(inv_path), "--node", "node-a", "--device", "/dev/sdz", "--cache", str(cache_dir)]
    out = subprocess.check_output(cmd, cwd=ROOT)
    plan = json.loads(out)
    assert plan["node"] == "node-a"
    assert any(a["type"] == "fetch" for a in plan["actions"])


def test_burn_dry_run(tmp_path):
    dummy = tmp_path / "dummy.img"
    dummy.write_bytes(b"dummy")
    import hashlib

    checksum = "sha256:" + hashlib.sha256(dummy.read_bytes()).hexdigest()
    inv_path = write_inv(tmp_path, dummy, checksum)
    cache_dir = tmp_path / "cache"
    cmd = [
        "go",
        "run",
        "./cmd/metis",
        "burn",
        "--inventory",
        str(inv_path),
        "--node",
        "node-a",
        "--device",
        "/dev/sdz",
        "--cache",
        str(cache_dir),
    ]
    out = subprocess.check_output(cmd, cwd=ROOT, text=True)
    assert "Dry run" in out or "Plan for" in out
