"""Tests for register_from_classification CLI (STATE-WP-0065 P3)."""
from __future__ import annotations

import json
import subprocess
import sys
from pathlib import Path

import pytest

REPO_ROOT = Path(__file__).resolve().parent.parent
SCRIPT = REPO_ROOT / "scripts" / "register_from_classification.py"


def test_cli_help():
    result = subprocess.run(
        [sys.executable, str(SCRIPT), "--help"],
        capture_output=True,
        text=True,
        cwd=REPO_ROOT,
    )
    assert result.returncode == 0
    assert "--repo-path" in result.stdout
    assert "--bulk" in result.stdout
    assert "--dry-run" in result.stdout


@pytest.mark.asyncio
async def test_dry_run_repo_path_state_hub():
    sys.path.insert(0, str(REPO_ROOT))
    from scripts.register_from_classification import run_registration
    import argparse

    args = argparse.Namespace(
        repo_path=str(REPO_ROOT),
        slug=None,
        bulk=False,
        dry_run=True,
        api=False,
        db=False,
        api_base="http://127.0.0.1:8000",
        json=False,
    )
    report = await run_registration(args)
    counts = report.counts()
    assert counts["invalid"] == 0
    assert counts["registered"] + counts["updated"] + counts["skipped"] >= 1
    assert any(r.slug == "state-hub" for r in report.results)
    # Valid classification file is always parsed even when DB domains are absent.
    assert not any("repo_classification block" in r.detail for r in report.results)


def test_json_report_shape():
    result = subprocess.run(
        [
            sys.executable,
            str(SCRIPT),
            "--repo-path",
            str(REPO_ROOT),
            "--dry-run",
            "--json",
        ],
        capture_output=True,
        text=True,
        cwd=REPO_ROOT,
    )
    payload = json.loads(result.stdout)
    assert payload["summary"]["invalid"] == 0
    assert "summary" in payload
    assert "results" in payload
    assert set(payload["summary"]) == {"registered", "updated", "skipped", "invalid"}