"""Fixture-driven tests for connection validation rules."""

import pytest

from fixtures import workflows_dir
from valn8n_lib.rules import get_rules
from valn8n_lib.validator import validate_workflow

FIXTURE_DIR = workflows_dir() / "test_connections"
BROKENZIE_DIR = workflows_dir() / "test_brokenzie619"


def _discover_cases() -> list[str]:
    """Discover test cases from .lst companion files."""
    return sorted(p.stem for p in FIXTURE_DIR.glob("*.lst"))


@pytest.mark.parametrize("case", _discover_cases())
def test_connection_rule(case: str) -> None:
    lst_path = FIXTURE_DIR / f"{case}.lst"
    json_path = FIXTURE_DIR / f"{case}.json"
    assert json_path.exists(), f"Missing fixture: {json_path}"

    expected = sorted(line.strip() for line in lst_path.read_text().splitlines() if line.strip())

    diagnostics = validate_workflow(json_path, rules=get_rules())
    nd06_diags = [d for d in diagnostics if d.code.code.startswith("ND06")]
    actual = sorted(d.code.code for d in nd06_diags)

    assert actual == expected, f"{case}: expected {expected}, got {actual}"


def test_working_3859_no_nd06() -> None:
    """Working workflow 3859 should produce no ND06xx diagnostics."""
    wf_path = (
        BROKENZIE_DIR
        / "3859-ai-customer-support-assistant-whatsapp-ready-works-for-any-business.json"
    )
    diagnostics = validate_workflow(wf_path, rules=get_rules())
    nd06_diags = [d for d in diagnostics if d.code.code.startswith("ND06")]
    assert nd06_diags == [], f"Unexpected ND06xx diagnostics: {[d.code.code for d in nd06_diags]}"


def test_broken_1521_has_nd0601() -> None:
    """Broken workflow 1521 should flag unconnected nodes."""
    wf_path = BROKENZIE_DIR / "1521_Whatsapp_Stickynote_Automation_Webhook.json"
    diagnostics = validate_workflow(wf_path, rules=get_rules())
    nd0601_diags = [d for d in diagnostics if d.code.code == "ND0601"]
    # All non-trigger, non-sticky nodes are disconnected (connections use UUID keys)
    assert len(nd0601_diags) == 10


def test_broken_1521_has_nd0602() -> None:
    """Broken workflow 1521 should flag dangling connection references."""
    wf_path = BROKENZIE_DIR / "1521_Whatsapp_Stickynote_Automation_Webhook.json"
    diagnostics = validate_workflow(wf_path, rules=get_rules())
    nd0602_diags = [d for d in diagnostics if d.code.code == "ND0602"]
    # 3 dangling source keys (UUIDs) + 19 dangling destination targets
    assert len(nd0602_diags) == 22
