#!/usr/bin/env python3
"""Enforce line and branch coverage thresholds from coverage.json."""

from __future__ import annotations

import json
import sys
from pathlib import Path

LINE_THRESHOLD = 90.0
BRANCH_THRESHOLD = 85.0


def _pct(numerator: float, denominator: float) -> float:
    if denominator <= 0:
        return 100.0
    return (numerator / denominator) * 100.0


def main() -> int:
    coverage_path = Path("coverage.json")
    if not coverage_path.exists():
        print("coverage.json not found")
        return 1

    payload = json.loads(coverage_path.read_text(encoding="utf-8"))
    totals = payload.get("totals", {})

    line_pct = float(totals.get("percent_covered", 0.0))
    covered_branches = float(totals.get("covered_branches", 0.0))
    num_branches = float(totals.get("num_branches", 0.0))
    branch_pct = _pct(covered_branches, num_branches)

    print(
        f"coverage line={line_pct:.2f}% (threshold {LINE_THRESHOLD:.2f}%) "
        f"branch={branch_pct:.2f}% (threshold {BRANCH_THRESHOLD:.2f}%)"
    )

    failed = False
    if line_pct < LINE_THRESHOLD:
        print("line coverage threshold failed")
        failed = True
    if branch_pct < BRANCH_THRESHOLD:
        print("branch coverage threshold failed")
        failed = True
    return 1 if failed else 0


if __name__ == "__main__":
    sys.exit(main())
