# Copyright (C) 2026 GoodData Corporation

"""Repository readiness checks for AIDA.

Why:
- The packaged AIDA MCP server can be installed system-wide (wheel), then used in many repos.
- Without repo-local config under `.aida/`, validation and rules retrieval can behave incorrectly by
  falling back to bundled defaults.
- Tools must be safe-by-default in uninitialized repositories.
"""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

from aida_mcp.utils.aida_paths import get_repo_config_root
from aida_mcp.utils.repo_config_versions import collect_repo_config_statuses

REQUIRED_VALIDATE_FILES: tuple[str, ...] = (
    "change_domains.yaml",
    "validation_policy.yaml",
    "validation_registry.yaml",
)


@dataclass(frozen=True, slots=True)
class RepoReadiness:
    workspace_root: Path
    config_root: Path
    config_root_exists: bool
    missing_validate_files: tuple[str, ...]
    outdated_config_versions: tuple[str, ...]
    rules_dir_exists: bool

    @property
    def validate_ready(self) -> bool:
        return self.config_root_exists and not self.missing_validate_files

    @property
    def rules_ready(self) -> bool:
        # Rules can be empty (repo may rely on embedded general rules), but the repo should still
        # explicitly opt into AIDA by having a config root.
        return self.config_root_exists


def check_repo_readiness(*, workspace_root: Path) -> RepoReadiness:
    config_root = get_repo_config_root(workspace_root)
    config_root_exists = config_root.exists()

    missing: list[str] = []
    if config_root_exists:
        for name in REQUIRED_VALIDATE_FILES:
            if not (config_root / name).exists():
                missing.append(name)

    rules_dir_exists = (config_root / "rules").exists() if config_root_exists else False

    return RepoReadiness(
        workspace_root=workspace_root,
        config_root=config_root,
        config_root_exists=config_root_exists,
        missing_validate_files=tuple(missing),
        outdated_config_versions=tuple(
            status.name for status in collect_repo_config_statuses(workspace_root=workspace_root) if status.outdated
        )
        if config_root_exists
        else (),
        rules_dir_exists=rules_dir_exists,
    )
