"""Team coding standards loaded from a markdown file (docs/CODING_STANDARDS.md)."""

from __future__ import annotations

import re
from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Tuple

import structlog

from packages.config import Settings, get_settings

logger = structlog.get_logger(__name__)

PROJECT_ROOT = Path(__file__).resolve().parents[2]

_RULE = re.compile(
    r"^\s*[-*]\s*\*\*(?P<id>[A-Z]+-\d+)\*\*\s+(?P<level>MUST|SHOULD)\s*(?P<auto>\[auto\])?\s*:?\s*(?P<text>.+)$"
)
_SECTION = re.compile(r"^##\s+(?P<name>.+?)\s*$")


@dataclass
class StandardRule:
    id: str
    level: str  # MUST | SHOULD
    text: str
    section: str = ""
    auto: bool = False

    @property
    def severity(self) -> str:
        return "high" if self.level == "MUST" else "medium"


@dataclass
class CodingStandards:
    text: str = ""
    rules: Dict[str, StandardRule] = field(default_factory=dict)
    path: str = ""

    def has(self, rule_id: str) -> bool:
        return rule_id in self.rules

    def prompt_block(
        self,
        max_chars: int = 6000,
        sections: Optional[Iterable[str]] = None,
        rule_ids: Optional[Iterable[str]] = None,
    ) -> str:
        """Rules for an LLM prompt.

        With ``sections`` / ``rule_ids``, only rules under a matching heading (case-insensitive
        prefix) or with a listed ID are included.
        """
        if not self.rules:
            return "(no coding standards file loaded)"
        wanted = [s.lower() for s in sections] if sections else []
        ids = set(rule_ids or [])
        filtered = bool(wanted or ids)
        lines: List[str] = []
        current = None
        for rule in self.rules.values():
            if filtered and rule.id not in ids and not any(rule.section.lower().startswith(w) for w in wanted):
                continue
            if rule.section != current:
                current = rule.section
                lines.append(f"{current}:")
            lines.append(f"- {rule.id} {rule.level}: {rule.text}")
        block = "\n".join(lines) or "(no matching rules)"
        if len(block) > max_chars:
            block = block[:max_chars] + "\n... (truncated)"
        return block


def parse_coding_standards(text: str, path: str = "") -> CodingStandards:
    rules: Dict[str, StandardRule] = {}
    section = ""
    for line in (text or "").splitlines():
        sm = _SECTION.match(line)
        if sm:
            section = sm.group("name")
            continue
        rm = _RULE.match(line)
        if rm:
            rules[rm.group("id")] = StandardRule(
                id=rm.group("id"),
                level=rm.group("level"),
                text=rm.group("text").strip(),
                section=section,
                auto=bool(rm.group("auto")),
            )
    return CodingStandards(text=text or "", rules=rules, path=path)


def resolve_standards_path(settings: Settings) -> Path:
    p = Path(settings.coding_standards_path or "docs/CODING_STANDARDS.md")
    return p if p.is_absolute() else PROJECT_ROOT / p


_cache: Dict[str, Tuple[float, CodingStandards]] = {}


def load_coding_standards(settings: Optional[Settings] = None) -> CodingStandards:
    """Load and parse the standards file; re-read when the file changes."""
    settings = settings or get_settings()
    path = resolve_standards_path(settings)
    key = str(path)
    try:
        mtime = path.stat().st_mtime
    except OSError:
        logger.warning("coding_standards_missing", path=key)
        return CodingStandards(path=key)
    cached = _cache.get(key)
    if cached and cached[0] == mtime:
        return cached[1]
    standards = parse_coding_standards(path.read_text(encoding="utf-8"), key)
    _cache[key] = (mtime, standards)
    return standards
