"""FU-8a / GAP-21: sync --verify drift-gate logic (offline)."""
from __future__ import annotations

import importlib.util
from pathlib import Path

_SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "sync_agents_across_companies.py"
_spec = importlib.util.spec_from_file_location("sync_agents", _SCRIPT)
sync = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(sync)


def _agent(name, adapter="claude_code", cfg=None):
    return {"id": f"id-{name}", "name": name, "adapter_type": adapter,
            "adapter_config": cfg or {"model": "x"}, "runtime_config": {}, "metadata": {},
            "budget_monthly_cents": 0, "icon": "", "title": "", "role": "", "agent_api_keys": []}


def test_verify_exit_code_clean_is_zero():
    assert sync._verify_exit_code(plan=[], mismatches=[], missing=[]) == 0


def test_verify_exit_code_drift_is_nonzero():
    assert sync._verify_exit_code(plan=[("m", "mi", {"x": 1})], mismatches=[], missing=[]) == 1


def test_verify_exit_code_adapter_mismatch_is_nonzero():
    assert sync._verify_exit_code(plan=[], mismatches=["עוזר משפטי"], missing=[]) == 1


def test_verify_exit_code_missing_is_nonzero():
    assert sync._verify_exit_code(plan=[], mismatches=[], missing=["סוכן"]) == 1


def test_build_drift_report_flags_adapter_mismatch():
    master = [_agent("A", adapter="claude_code")]
    mirror_by_name = {"A": _agent("A", adapter="deepseek_local")}
    rep = sync.build_drift_report(master, mirror_by_name, mirror_skills=set(), only=None)
    assert "A" in rep["mismatches"]
    assert rep["plan"] == []


def test_build_drift_report_flags_missing_and_plan():
    master = [_agent("A"), _agent("B")]
    mirror_by_name = {"B": _agent("B", cfg={"model": "different"})}
    rep = sync.build_drift_report(master, mirror_by_name, mirror_skills=set(), only=None)
    assert "A" in rep["missing"]
    assert any(p[0]["name"] == "B" for p in rep["plan"])
