from __future__ import annotations

import json
from pathlib import Path

import pytest
from cognite_data_quality._rules import load_json_rules, load_rules, load_yaml_rules


def test_load_rules_ttl(tmp_rules_dir: Path) -> None:
    ttl_path = tmp_rules_dir / "rules.ttl"
    ttl_path.write_text("@prefix sh: <http://www.w3.org/ns/shacl#> .", encoding="utf-8")

    rules, config = load_rules(ttl_path, format="ttl")
    assert "shacl" in rules
    assert config.datamodel is None


def test_load_rules_json(tmp_rules_dir: Path) -> None:
    json_path = tmp_rules_dir / "rules.json"
    json_content = {
        "quality": [
            {
                "ruleSetExternalId": "set1",
                "ruleSetVersion": "1.0",
                "ruleDefinitions": [
                    {
                        "@context": {"sh": "http://www.w3.org/ns/shacl#"},
                        "@id": "ex:Shape",
                        "@type": "sh:NodeShape",
                    }
                ],
            }
        ]
    }
    json_path.write_text(json.dumps(json_content), encoding="utf-8")

    rules = load_json_rules(json_path)
    assert "sh:NodeShape" in rules


def test_load_rules_yaml(tmp_rules_dir: Path) -> None:
    ttl_path = tmp_rules_dir / "rules.ttl"
    ttl_path.write_text("@prefix sh: <http://www.w3.org/ns/shacl#> .", encoding="utf-8")

    yaml_path = tmp_rules_dir / "view.yaml"
    yaml_path.write_text(
        'view:\n  space: "sp"\n  external_id: "Model"\n  version: "v1"\ninstance_space: "inst"\nshacl_rules:\n  file: "rules.ttl"\ndatamodel:\n  space: "sp"\n  external_id: "Model"\n  version: "v1"\nvalidation:\n  auto_load_depth: 3\n  verbose: false\nrecords:\n  rule_set_id: "Set"\n  rule_set_version: "1.0"',  # noqa: E501
        encoding="utf-8",
    )

    rules, config = load_yaml_rules(yaml_path, shacl_base_dir=tmp_rules_dir)
    assert "shacl" in rules
    assert config.datamodel is not None
    assert config.auto_load_depth == 3


def test_load_json_rules_missing_quality(tmp_rules_dir: Path) -> None:
    json_path = tmp_rules_dir / "rules.json"
    json_path.write_text(json.dumps({"quality": []}), encoding="utf-8")

    with pytest.raises(ValueError, match="quality"):
        load_json_rules(json_path)


def test_load_yaml_rules_missing_shacl(tmp_rules_dir: Path) -> None:
    yaml_path = tmp_rules_dir / "view.yaml"
    yaml_path.write_text("datamodel:\n  space: sp\n", encoding="utf-8")

    with pytest.raises(ValueError, match="shacl_rules"):
        load_yaml_rules(yaml_path)


def test_load_rules_unknown_suffix(tmp_rules_dir: Path) -> None:
    unknown_path = tmp_rules_dir / "rules.unknown"
    unknown_path.write_text("content", encoding="utf-8")

    with pytest.raises(ValueError, match="infer rule format"):
        load_rules(unknown_path)
