"""validate_viz / script_syntax (Python + graph)."""

from __future__ import annotations

from aicd.kit import script_syntax, validate_viz


def test_graph_json_valid() -> None:
    r = validate_viz.validate_graph_json(
        [{"id": "a", "label": "A"}, {"id": "b"}],
        [{"from": "a", "to": "b"}],
    )
    assert r["ok"]
    assert "normalized" in r
    assert r["normalized"]["edges"][0]["from"] == "a"


def test_graph_json_bad_edge() -> None:
    r = validate_viz.validate_graph_json([{"id": "x"}], [{"from": "x", "to": "missing"}])
    assert not r["ok"]


def test_chartjs_ok() -> None:
    cfg = {
        "type": "bar",
        "data": {
            "labels": ["a", "b"],
            "datasets": [{"label": "s", "data": [1, 2]}],
        },
    }
    r = validate_viz.validate_chartjs_config(cfg)
    assert r["ok"]


def test_mermaid_issues_backticks() -> None:
    r = validate_viz.validate_mermaid_body("```mermaid\nx\n```")
    assert not r["ok"]


def test_html_viz_local_scripts_ok() -> None:
    html = """
<body>
<pre class="mermaid">flowchart LR
  A --> B
</pre>
<script src="res/chart.umd.min.js"></script>
<script src="res/mermaid.min.js"></script>
<script src="res/vis-network.min.js"></script>
<script>mermaid.initialize({});</script>
</body>
"""
    r = validate_viz.validate_html_viz_embed(html)
    assert r["ok"], r.get("issues")


def test_html_viz_remote_script_rejected() -> None:
    html = """
<pre class="mermaid">flowchart LR
  A --> B
</pre>
<script src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></script>
"""
    r = validate_viz.validate_html_viz_embed(html)
    assert not r["ok"]
    assert any("network_ref:" in i for i in r["issues"])


def test_html_viz_protocol_relative_rejected() -> None:
    html = '<script src="//cdn.example.com/lib.js"></script>'
    r = validate_viz.validate_html_viz_embed(html)
    assert not r["ok"]
    assert any("network_ref:" in i for i in r["issues"])


def test_html_viz_remote_img_rejected() -> None:
    html = '<img src="https://example.com/a.png" alt="x">'
    r = validate_viz.validate_html_viz_embed(html)
    assert not r["ok"]
    assert any("network_ref:" in i and "img" in i.lower() for i in r["issues"])


def test_html_viz_css_url_remote_rejected() -> None:
    html = "<style>body{background:url(https://x.test/bg.png)}</style>"
    r = validate_viz.validate_html_viz_embed(html)
    assert not r["ok"]
    assert any("network_ref:" in i for i in r["issues"])


def test_python_syntax() -> None:
    assert script_syntax.check_python("def f():\n    pass")["ok"]
    bad = script_syntax.check_python("def f(\n")
    assert not bad["ok"]
    assert bad.get("lineno")


def test_bat_heuristic() -> None:
    r = script_syntax.check_bat_heuristic("@echo off\n(echo a")
    assert r["ok"] and r.get("heuristic_only")
    assert any("parentheses" in w.lower() for w in r.get("warnings", []))
