from __future__ import annotations
import logging
import math
import os
import tempfile
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any

import yaml

logger = logging.getLogger(__name__)


class ConfigError(ValueError):
    """Raised when ``.botbrain/config.yaml`` is malformed or invalid."""


def _legacy_root_anchored_patterns(patterns: list[str]) -> list[str]:
    """Return exclude patterns whose depth semantics changed with root anchoring.

    Before the anchoring fix, a single-segment trailing-slash pattern such
    as ``build/`` had its slash stripped and excluded the segment at ANY
    depth; it now matches only the root-level directory. Hidden names
    (``.git/``, ``__pycache__/``) are excluded at any depth by a separate
    hardcoded rule, so their meaning never changed; globs and multi-segment
    prefixes were already root-anchored.
    """
    return [
        pattern for pattern in patterns
        if pattern.endswith("/")
        and "/" not in pattern[:-1]
        and not pattern.startswith(".")
        and not any(char in pattern for char in "*?[")
    ]


def _warn_legacy_root_anchored_patterns(patterns: list[str]) -> None:
    """Surface the silent scope change when loading a pre-fix exclude list.

    Configs saved by older versions (or hand-written with the old
    any-depth semantics in mind) keep working but match less than before;
    a monorepo relying on ``packages/*/build/`` exclusion would silently
    start indexing those artifacts. One aggregate warning keeps the
    migration path visible. A list that exactly matches the current
    defaults is a fresh save of the new semantics and stays silent.
    """
    affected = _legacy_root_anchored_patterns(patterns)
    if not affected or patterns == Config.default().exclude_patterns:
        return
    logger.warning(
        "project.exclude: %s now match only root-level directories "
        "(trailing slash = root-anchored prefix); use bare names "
        "(e.g. 'build', 'node_modules') to exclude at any depth",
        ", ".join(repr(pattern) for pattern in affected),
    )


def _validate_document_content_policy(config: Any) -> None:
    """Expose stored-content policy errors as normal configuration errors."""
    # Local import keeps the core config module lightweight and avoids a
    # runtime dependency cycle (document_content only imports Config for type
    # checking).
    from .build.document_content import DocumentContentError, DocumentContentPolicy

    try:
        DocumentContentPolicy.from_config(config)
    except DocumentContentError as exc:
        raise ConfigError(f"documents.stored_content: {exc}") from exc


def _validate_scan_patterns(config: "Config") -> None:
    """Reject scan include/exclude patterns that can never match in-project paths."""
    for field_name, patterns in (
        ("project.include", config.include_patterns),
        ("project.exclude", config.exclude_patterns),
    ):
        for pattern in patterns:
            raw = str(pattern).replace("\\", "/").strip()
            if raw.startswith("/"):
                raise ConfigError(
                    f"{field_name}: absolute pattern {pattern!r} is not allowed"
                )
            pat = raw.strip("/")
            if not pat:
                raise ConfigError(f"{field_name}: empty pattern is not allowed")
            if ".." in pat.split("/"):
                raise ConfigError(
                    f"{field_name}: '..' segments are not allowed in {pattern!r}"
                )


def _mapping(value: Any, field_name: str) -> dict[str, Any]:
    if not isinstance(value, dict):
        raise ConfigError(f"{field_name} must be a mapping")
    return value


def _string(value: Any, field_name: str) -> str:
    if not isinstance(value, str):
        raise ConfigError(f"{field_name} must be a string")
    return value


def _string_list(value: Any, field_name: str) -> list[str]:
    if not isinstance(value, list) or any(not isinstance(item, str) for item in value):
        raise ConfigError(f"{field_name} must be a list of strings")
    return list(value)


def _boolean(value: Any, field_name: str) -> bool:
    if type(value) is not bool:
        raise ConfigError(f"{field_name} must be a boolean")
    return value


def _number(value: Any, field_name: str) -> float:
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        raise ConfigError(f"{field_name} must be a number")
    number = float(value)
    if not math.isfinite(number):
        raise ConfigError(f"{field_name} must be finite")
    return number


def _integer(value: Any, field_name: str) -> int:
    if isinstance(value, bool) or not isinstance(value, int):
        raise ConfigError(f"{field_name} must be an integer")
    return value


def _choice(value: Any, field_name: str, choices: set[str]) -> str:
    value = _string(value, field_name)
    if value not in choices:
        expected = ", ".join(sorted(choices))
        raise ConfigError(f"{field_name} must be one of: {expected}")
    return value


@dataclass
class Config:
    project_name: str = ""
    languages: list[str] = field(default_factory=list)
    # Trailing-slash patterns (build/, dist/, ...) are root-anchored
    # prefixes, so nested source dirs like src/pkg/build/ stay indexed;
    # "node_modules" is bare on purpose to also exclude the nested
    # packages/*/node_modules trees of JS monorepos.
    exclude_patterns: list[str] = field(default_factory=lambda: [
        ".git/", "node_modules", "target/", "build/", "dist/",
        "__pycache__/", ".venv/", "vendor/",
        "*.generated.*", "*.pb.*", "*_pb2.*",
    ])
    include_patterns: list[str] = field(default_factory=list)
    search_strategy: str = "hybrid"
    index_body: bool = False
    parser_semantic_backend: str = "auto"
    model_precision: str = "int8"
    debounce_seconds: float = 5
    observer_type: str = "auto"
    watcher_enabled: bool = True
    reconcile_interval_seconds: int = 3600
    full_rebuild_threshold: float = 0.1
    storage_backend: str = "auto"
    max_commits: int = 10000
    document_content_include: list[str] = field(default_factory=list)
    document_content_exclude: list[str] = field(default_factory=list)
    document_content_max_file_bytes: int = 2 * 1024 * 1024
    document_content_max_total_bytes: int = 32 * 1024 * 1024
    document_content_on_limit: str = "error"
    graph_profile: str = "full"
    graph_public_api_include_support_types: bool = True
    graph_public_api_include_public_methods: bool = True
    graph_public_api_include_tests: bool = False
    graph_public_api_include_module_dependencies: bool = True
    wiki_enabled: bool = False
    wiki_cookie_file: str = ""
    wiki_output_dir: str = "docs/wiki"
    wiki_include_refs: bool = False
    wiki_include_children: bool = False

    @staticmethod
    def default() -> Config:
        return Config()

    @staticmethod
    def load(project_path: str) -> Config:
        from .paths import config_file as resolve_config_file

        config_file = resolve_config_file(Path(project_path))
        if not config_file.exists():
            return Config.default()

        try:
            with open(config_file, "r", encoding="utf-8") as f:
                loaded = yaml.safe_load(f)
        except (OSError, UnicodeError, yaml.YAMLError) as exc:
            raise ConfigError(f"cannot read {config_file}: {exc}") from exc

        data = {} if loaded is None else _mapping(loaded, "config")

        config = Config.default()

        if "project" in data:
            proj = _mapping(data["project"], "project")
            if "name" in proj:
                config.project_name = _string(proj["name"], "project.name")
            if "languages" in proj:
                config.languages = _string_list(proj["languages"], "project.languages")
            if "exclude" in proj:
                config.exclude_patterns = _string_list(proj["exclude"], "project.exclude")
                _warn_legacy_root_anchored_patterns(config.exclude_patterns)
            if "include" in proj:
                config.include_patterns = _string_list(proj["include"], "project.include")

        if "search" in data:
            search = _mapping(data["search"], "search")
            if "strategy" in search:
                config.search_strategy = _choice(
                    search["strategy"], "search.strategy",
                    {"keyword", "keyword+graph", "semantic", "hybrid"},
                )
            if "index_body" in search:
                config.index_body = _boolean(search["index_body"], "search.index_body")
            if "model_precision" in search:
                config.model_precision = _choice(
                    search["model_precision"], "search.model_precision", {"int8", "full"},
                )

        if "parsing" in data:
            parsing = _mapping(data["parsing"], "parsing")
            if "semantic_backend" in parsing:
                config.parser_semantic_backend = _choice(
                    parsing["semantic_backend"],
                    "parsing.semantic_backend",
                    {"off", "auto", "required"},
                )

        if "watcher" in data:
            w = _mapping(data["watcher"], "watcher")
            if "debounce_seconds" in w:
                config.debounce_seconds = max(
                    0.0, _number(w["debounce_seconds"], "watcher.debounce_seconds")
                )
            if "observer_type" in w:
                config.observer_type = _choice(
                    w["observer_type"], "watcher.observer_type",
                    {"auto", "polling", "native", "inotify"},
                )
            if "enabled" in w:
                config.watcher_enabled = _boolean(w["enabled"], "watcher.enabled")
            if "reconcile_interval_seconds" in w:
                config.reconcile_interval_seconds = max(
                    0,
                    _integer(
                        w["reconcile_interval_seconds"],
                        "watcher.reconcile_interval_seconds",
                    ),
                )
            if "full_rebuild_threshold" in w:
                threshold = _number(
                    w["full_rebuild_threshold"], "watcher.full_rebuild_threshold"
                )
                if not 0.0 <= threshold <= 1.0:
                    raise ConfigError("watcher.full_rebuild_threshold must be between 0 and 1")
                config.full_rebuild_threshold = threshold

        if "storage" in data:
            storage = _mapping(data["storage"], "storage")
            if "backend" in storage:
                config.storage_backend = _choice(
                    storage["backend"], "storage.backend", {"auto", "json", "sqlite"},
                )

        if "history" in data:
            history = _mapping(data["history"], "history")
            if "max_commits" in history:
                max_commits = _integer(history["max_commits"], "history.max_commits")
                if max_commits < 0:
                    raise ConfigError("history.max_commits must be non-negative")
                config.max_commits = max_commits

        if "documents" in data:
            documents = _mapping(data["documents"], "documents")
            if "stored_content" in documents:
                stored = _mapping(
                    documents["stored_content"], "documents.stored_content"
                )
                if "include" in stored:
                    config.document_content_include = _string_list(
                        stored["include"], "documents.stored_content.include"
                    )
                if "exclude" in stored:
                    config.document_content_exclude = _string_list(
                        stored["exclude"], "documents.stored_content.exclude"
                    )
                if "max_file_bytes" in stored:
                    max_file_bytes = _integer(
                        stored["max_file_bytes"],
                        "documents.stored_content.max_file_bytes",
                    )
                    if max_file_bytes <= 0:
                        raise ConfigError(
                            "documents.stored_content.max_file_bytes must be positive"
                        )
                    config.document_content_max_file_bytes = max_file_bytes
                if "max_total_bytes" in stored:
                    max_total_bytes = _integer(
                        stored["max_total_bytes"],
                        "documents.stored_content.max_total_bytes",
                    )
                    if max_total_bytes <= 0:
                        raise ConfigError(
                            "documents.stored_content.max_total_bytes must be positive"
                        )
                    config.document_content_max_total_bytes = max_total_bytes
                if "on_limit" in stored:
                    config.document_content_on_limit = _choice(
                        stored["on_limit"],
                        "documents.stored_content.on_limit",
                        {"error", "omit"},
                    )

        if "graph" in data:
            graph = _mapping(data["graph"], "graph")
            if "profile" in graph:
                config.graph_profile = _choice(
                    graph["profile"], "graph.profile", {"full", "mini"},
                )
            if "public_api" in graph:
                public_api = _mapping(graph["public_api"], "graph.public_api")
                if "include_support_types" in public_api:
                    config.graph_public_api_include_support_types = _boolean(
                        public_api["include_support_types"],
                        "graph.public_api.include_support_types",
                    )
                if "include_public_methods" in public_api:
                    config.graph_public_api_include_public_methods = _boolean(
                        public_api["include_public_methods"],
                        "graph.public_api.include_public_methods",
                    )
                if "include_tests" in public_api:
                    config.graph_public_api_include_tests = _boolean(
                        public_api["include_tests"],
                        "graph.public_api.include_tests",
                    )
                if "include_module_dependencies" in public_api:
                    config.graph_public_api_include_module_dependencies = _boolean(
                        public_api["include_module_dependencies"],
                        "graph.public_api.include_module_dependencies",
                    )

        if "wiki" in data:
            wiki = _mapping(data["wiki"], "wiki")
            if "enabled" in wiki:
                config.wiki_enabled = _boolean(wiki["enabled"], "wiki.enabled")
            if "cookie_file" in wiki:
                config.wiki_cookie_file = _string(
                    wiki["cookie_file"], "wiki.cookie_file"
                )
            if "output_dir" in wiki:
                config.wiki_output_dir = _string(
                    wiki["output_dir"], "wiki.output_dir"
                )
            if "include_refs" in wiki:
                config.wiki_include_refs = _boolean(
                    wiki["include_refs"], "wiki.include_refs"
                )
            if "include_children" in wiki:
                config.wiki_include_children = _boolean(
                    wiki["include_children"], "wiki.include_children"
                )

        config.validate()
        return config

    def validate(self) -> None:
        """Validate cross-field policies after programmatic overrides."""
        _validate_document_content_policy(self)
        _validate_scan_patterns(self)
        if self.graph_profile not in {"full", "mini"}:
            raise ConfigError(
                f"graph.profile must be one of: full, mini (got {self.graph_profile!r})"
            )
        if self.parser_semantic_backend not in {"off", "auto", "required"}:
            raise ConfigError(
                "parsing.semantic_backend must be one of: off, auto, required"
            )

    def save(self, project_path: str) -> None:
        """Persist config to ``<project>/.botbrain/config.yaml``."""
        from .paths import config_file as resolve_config_file

        self.validate()
        config_file = resolve_config_file(Path(project_path))
        config_file.parent.mkdir(parents=True, exist_ok=True)
        data = {
            "project": {
                "name": self.project_name,
                "languages": self.languages,
                "exclude": self.exclude_patterns,
                "include": self.include_patterns,
            },
            "search": {
                "strategy": self.search_strategy,
                "index_body": self.index_body,
                "model_precision": self.model_precision,
            },
            "parsing": {
                "semantic_backend": self.parser_semantic_backend,
            },
            "watcher": {
                "enabled": self.watcher_enabled,
                "debounce_seconds": self.debounce_seconds,
                "observer_type": self.observer_type,
                "reconcile_interval_seconds": self.reconcile_interval_seconds,
                "full_rebuild_threshold": self.full_rebuild_threshold,
            },
            "storage": {
                "backend": self.storage_backend,
            },
            "history": {
                "max_commits": self.max_commits,
            },
            "documents": {
                "stored_content": {
                    "include": self.document_content_include,
                    "exclude": self.document_content_exclude,
                    "max_file_bytes": self.document_content_max_file_bytes,
                    "max_total_bytes": self.document_content_max_total_bytes,
                    "on_limit": self.document_content_on_limit,
                },
            },
            "graph": {
                "profile": self.graph_profile,
                "public_api": {
                    "include_support_types": self.graph_public_api_include_support_types,
                    "include_public_methods": self.graph_public_api_include_public_methods,
                    "include_tests": self.graph_public_api_include_tests,
                    "include_module_dependencies": self.graph_public_api_include_module_dependencies,
                },
            },
            "wiki": {
                "enabled": self.wiki_enabled,
                "cookie_file": self.wiki_cookie_file,
                "output_dir": self.wiki_output_dir,
                "include_refs": self.wiki_include_refs,
                "include_children": self.wiki_include_children,
            },
        }
        temp_path: Path | None = None
        try:
            with tempfile.NamedTemporaryFile(
                "w",
                encoding="utf-8",
                dir=config_file.parent,
                prefix=f".{config_file.name}.",
                suffix=".tmp",
                delete=False,
            ) as f:
                temp_path = Path(f.name)
                yaml.dump(
                    data,
                    f,
                    allow_unicode=True,
                    default_flow_style=False,
                    sort_keys=False,
                )
                f.flush()
                os.fsync(f.fileno())
            os.replace(temp_path, config_file)
            temp_path = None
        except (OSError, UnicodeError, yaml.YAMLError) as exc:
            raise ConfigError(f"cannot write {config_file}: {exc}") from exc
        finally:
            if temp_path is not None:
                try:
                    temp_path.unlink(missing_ok=True)
                except OSError:
                    pass