"""Rule suppression helpers with reason tracking."""

from __future__ import annotations

import json
import time
from pathlib import Path
from typing import Dict, List


REASONS_FILE = ".oncecheckignore.reasons.json"


def _ignore_path(project_root: Path) -> Path:
    return project_root / ".oncecheckignore"


def _reasons_path(project_root: Path) -> Path:
    return project_root / REASONS_FILE


def add_suppression(project_root: Path, rule_id: str, reason: str) -> None:
    rid = rule_id.strip().upper()
    if not rid:
        raise ValueError("rule_id is required")
    rp = _ignore_path(project_root)
    existing = set()
    if rp.exists():
        for line in rp.read_text().splitlines():
            line = line.strip()
            if line and not line.startswith("#"):
                existing.add(line)
    if rid not in existing:
        with rp.open("a") as f:
            if rp.stat().st_size > 0:
                f.write("\n")
            f.write(rid + "\n")
    _record_reason(project_root, rid, reason)


def list_suppressions(project_root: Path) -> List[str]:
    rp = _ignore_path(project_root)
    if not rp.exists():
        return []
    out = []
    for line in rp.read_text().splitlines():
        line = line.strip()
        if line and not line.startswith("#"):
            out.append(line)
    return out


def get_suppression_reasons(project_root: Path) -> Dict[str, dict]:
    path = _reasons_path(project_root)
    if not path.exists():
        return {}
    try:
        data = json.loads(path.read_text())
    except (json.JSONDecodeError, OSError):
        return {}
    return data if isinstance(data, dict) else {}


def _record_reason(project_root: Path, rule_id: str, reason: str) -> None:
    reasons = get_suppression_reasons(project_root)
    reasons[rule_id] = {
        "reason": reason.strip() or "no reason provided",
        "updated_at": int(time.time()),
    }
    path = _reasons_path(project_root)
    path.write_text(json.dumps(reasons, indent=2, sort_keys=True))
