"""Custom rules loader for LLM system prompts.

This module loads user-defined rules from .emdash/rules/*.md files
and adds them to the LLM system prompt.
"""

from pathlib import Path
from typing import Optional

from emdash.utils.logger import log


def get_rules_dir(repo_root: Optional[Path] = None) -> Path:
    """Get the rules directory path.

    Args:
        repo_root: Repository root. Uses cwd if not provided.

    Returns:
        Path to .emdash/rules/
    """
    if repo_root is None:
        repo_root = Path.cwd()
    return repo_root / ".emdash" / "rules"


def load_rules(repo_root: Optional[Path] = None) -> str:
    """Load all markdown rules from .emdash/rules/ directory.

    Reads all .md files in the rules directory and concatenates them
    with headers indicating the source file.

    Args:
        repo_root: Repository root directory. Uses cwd if not provided.

    Returns:
        Combined rules content as a string, empty if no rules found.

    Example:
        rules = load_rules(Path("."))
        if rules:
            system_prompt = f"{base_prompt}\\n\\n{rules}"
    """
    rules_dir = get_rules_dir(repo_root)

    if not rules_dir.exists():
        log.debug(f"Rules directory not found: {rules_dir}")
        return ""

    # Find all markdown files
    md_files = sorted(rules_dir.glob("*.md"))

    if not md_files:
        log.debug(f"No .md files found in {rules_dir}")
        return ""

    # Load and combine rules
    rules_parts = []
    for md_file in md_files:
        try:
            content = md_file.read_text(encoding="utf-8").strip()
            if content:
                rules_parts.append(f"## {md_file.stem}\n\n{content}")
                log.debug(f"Loaded rules from {md_file.name}")
        except Exception as e:
            log.warning(f"Failed to read rules file {md_file}: {e}")

    if not rules_parts:
        return ""

    # Combine with header
    combined = "\n\n".join(rules_parts)
    rules_content = f"# Custom Rules\n\n{combined}"

    log.info(f"Loaded {len(rules_parts)} rule file(s) from {rules_dir}")
    return rules_content


def ensure_rules_dir(repo_root: Optional[Path] = None) -> Path:
    """Ensure the rules directory exists.

    Args:
        repo_root: Repository root. Uses cwd if not provided.

    Returns:
        Path to the created/existing rules directory.
    """
    rules_dir = get_rules_dir(repo_root)
    rules_dir.mkdir(parents=True, exist_ok=True)
    return rules_dir
