# retoor <retoor@molodetz.nl>

from devplacepy.routers.tools.isslop import _signal_groups


def _signal(code, severity="weak", line=1, title="t"):
    return {"code": code, "title": title, "severity": severity, "axis": "quality", "weight": 1.0, "line": line, "evidence": ""}


def test_signal_groups_deduplicates_with_counts():
    groups = _signal_groups(
        [
            _signal("INJECTION_RISK", "strong", 10),
            _signal("INJECTION_RISK", "strong", 22),
            _signal("INJECTION_RISK", "strong", 31),
            _signal("TEXTBOOK_NAMING", "medium", 5),
        ]
    )
    assert [group["code"] for group in groups] == ["INJECTION_RISK", "TEXTBOOK_NAMING"]
    assert groups[0]["count"] == 3
    assert groups[0]["lines"] == [10, 22, 31]
    assert groups[1]["count"] == 1


def test_signal_groups_orders_by_severity_then_count():
    groups = _signal_groups(
        [_signal("WEAK_A", "weak")] * 5
        + [_signal("MEDIUM_A", "medium")]
        + [_signal("STRONG_A", "strong")]
        + [_signal("WEAK_B", "weak")] * 2
    )
    assert [group["code"] for group in groups] == ["STRONG_A", "MEDIUM_A", "WEAK_A", "WEAK_B"]


def test_signal_groups_tolerates_malformed_entries():
    groups = _signal_groups(["not-a-dict", {"code": "X", "severity": "strong", "line": "n/a"}])
    assert len(groups) == 1
    assert groups[0]["lines"] == []


def test_linkify_sources_rewrites_every_reference_form():
    from devplacepy.routers.tools.isslop import _linkify_sources

    markdown = (
        "The `src/libs/Env.ts:12` line in `src/libs/Env.ts` and bare src/libs/Env.ts plus "
        "src/libs/Env.ts:30 with signal AI_SIGNATURE and `unknown.ts`."
    )
    result = _linkify_sources(markdown, "uid1", {"src/libs/Env.ts"}, {"AI_SIGNATURE"})
    assert "[`src/libs/Env.ts:12`](/tools/isslop/uid1/source?path=src%2Flibs%2FEnv.ts&line=12#L12)" in result
    assert "[`src/libs/Env.ts`](/tools/isslop/uid1/source?path=src%2Flibs%2FEnv.ts)" in result
    assert "[src/libs/Env.ts:30](/tools/isslop/uid1/source?path=src%2Flibs%2FEnv.ts&line=30#L30)" in result
    assert "[AI_SIGNATURE](/docs/isslop-checks.html)" in result
    assert "`unknown.ts`" in result


def test_linkify_sources_never_rewrites_inside_generated_links():
    from devplacepy.routers.tools.isslop import _linkify_sources

    markdown = "`a/b.ts` then `a/b.ts` again"
    result = _linkify_sources(markdown, "uid1", {"a/b.ts"}, set())
    assert result.count("](/tools/isslop/uid1/source?path=a%2Fb.ts)") == 2
    assert "[[" not in result and "]](" not in result


def test_source_url_encodes_path_and_line():
    from devplacepy.routers.tools.isslop import _source_url

    assert _source_url("u1", "a b/c.ts") == "/tools/isslop/u1/source?path=a%20b%2Fc.ts"
    assert _source_url("u1", "x.ts", 12).endswith("&line=12#L12")
