"""Config loading, .pjctxignore parsing, repo root detection."""

from __future__ import annotations

import json
import os
from pathlib import Path
from typing import Any

PJCTX_DIR = ".pjctx"
CONFIG_FILE = "config.json"
IGNORE_FILE = ".pjctxignore"

DEFAULT_CONFIG: dict[str, Any] = {
    "auto_save_interval": 300,
    "max_contexts_per_branch": 50,
    "default_format": "default",
    "watch_ignore": [],
}


def find_repo_root(start: Path | None = None) -> Path | None:
    """Walk up from start to find the nearest directory containing .git/."""
    current = (start or Path.cwd()).resolve()
    while True:
        if (current / ".git").exists():
            return current
        parent = current.parent
        if parent == current:
            return None
        current = parent


def get_pjctx_dir(repo_root: Path) -> Path:
    return repo_root / PJCTX_DIR


def load_config(repo_root: Path) -> dict[str, Any]:
    config_path = get_pjctx_dir(repo_root) / CONFIG_FILE
    if config_path.exists():
        with open(config_path, "r") as f:
            user_cfg = json.load(f)
        merged = {**DEFAULT_CONFIG, **user_cfg}
        return merged
    return dict(DEFAULT_CONFIG)


def save_config(repo_root: Path, config: dict[str, Any]) -> None:
    config_path = get_pjctx_dir(repo_root) / CONFIG_FILE
    config_path.parent.mkdir(parents=True, exist_ok=True)
    tmp = config_path.with_suffix(".tmp")
    with open(tmp, "w") as f:
        json.dump(config, f, indent=2)
        f.write("\n")
    os.replace(tmp, config_path)


def load_ignore_patterns(repo_root: Path) -> list[str]:
    """Load .pjctxignore patterns (one glob per line, # comments)."""
    ignore_path = repo_root / IGNORE_FILE
    if not ignore_path.exists():
        return []
    patterns: list[str] = []
    for line in ignore_path.read_text().splitlines():
        line = line.strip()
        if line and not line.startswith("#"):
            patterns.append(line)
    return patterns
