from __future__ import annotations

import re
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[1]


def _read_repo_text(path: str) -> str:
    return (REPO_ROOT / path).read_text(encoding="utf-8")


def _extract_toml_section(text: str, section_name: str) -> str:
    pattern = rf"^\[{re.escape(section_name)}\]\s*$\n(?P<body>.*?)(?=^\[.+\]\s*$|\Z)"
    match = re.search(pattern, text, flags=re.MULTILINE | re.DOTALL)
    assert match is not None, f"missing TOML section [{section_name}]"
    return match.group("body")


def test_coverage_threshold_aligned_between_pyproject_justfile_and_ci_workflow() -> None:
    pyproject = _read_repo_text("pyproject.toml")
    coverage_section = _extract_toml_section(pyproject, "tool.coverage.report")
    match = re.search(r"^\s*fail_under\s*=\s*(\d+)\s*$", coverage_section, flags=re.MULTILINE)
    assert match is not None, "missing coverage fail_under in pyproject"
    canonical_threshold = int(match.group(1))

    justfile = _read_repo_text("justfile")
    just_thresholds = {int(raw) for raw in re.findall(r"--cov-fail-under=(\d+)", justfile)}
    assert just_thresholds == {canonical_threshold}

    ci_workflow = _read_repo_text(".github/workflows/ci-cd.yml")
    workflow_thresholds = {int(raw) for raw in re.findall(r"--cov-fail-under=(\d+)", ci_workflow)}
    assert workflow_thresholds == {canonical_threshold}


def test_deptry_dep002_ignores_eval_only_analytics_dependencies() -> None:
    pyproject = _read_repo_text("pyproject.toml")
    deptry_ignores_section = _extract_toml_section(pyproject, "tool.deptry.per_rule_ignores")
    match = re.search(
        r"^\s*DEP002\s*=\s*\[(?P<body>.*?)\]\s*$",
        deptry_ignores_section,
        flags=re.MULTILINE | re.DOTALL,
    )
    assert match is not None, "missing DEP002 ignore list in deptry config"
    dep002_ignored_packages = set(re.findall(r'"([^"]+)"', match.group("body")))
    assert {"polars", "scikit-learn", "scipy"}.issubset(dep002_ignored_packages)
