"""Path conventions for the Mais Humana platform."""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

from .models import as_plain_data


@dataclass(slots=True)
class PlatformPaths:
    ecosystem_root: Path
    project_root: Path
    central_folder: Path

    @property
    def sqlite_path(self) -> Path:
        return self.central_folder / "controle-semantico.sqlite"

    @property
    def reports_dir(self) -> Path:
        return self.central_folder / "reports"

    @property
    def orders_executive_dir(self) -> Path:
        return self.central_folder / "orders" / "executivas"

    @property
    def orders_managerial_dir(self) -> Path:
        return self.central_folder / "orders" / "gerenciais"

    @property
    def project_data_dir(self) -> Path:
        return self.project_root / "dados"

    @property
    def project_docx_dir(self) -> Path:
        return self.project_root / "relatorios-docx"

    def ensure(self) -> None:
        for path in (
            self.project_root,
            self.central_folder,
            self.reports_dir,
            self.orders_executive_dir,
            self.orders_managerial_dir,
            self.project_data_dir,
            self.project_docx_dir,
        ):
            path.mkdir(parents=True, exist_ok=True)

    def to_dict(self) -> dict[str, object]:
        return as_plain_data(
            {
                "ecosystem_root": self.ecosystem_root,
                "project_root": self.project_root,
                "central_folder": self.central_folder,
                "sqlite_path": self.sqlite_path,
                "reports_dir": self.reports_dir,
                "orders_executive_dir": self.orders_executive_dir,
                "orders_managerial_dir": self.orders_managerial_dir,
            }
        )


def default_paths(root: str | Path = "G:/_codex-git") -> PlatformPaths:
    base = Path(root)
    return PlatformPaths(
        ecosystem_root=base,
        project_root=base / "tudo-para-ia-mais-humana",
        central_folder=base
        / "nucleo-gestao-operacional"
        / "central-de-ordem-de-servico"
        / "projects"
        / "15_repo_tudo-para-ia-mais-humana-platform",
    )


def assert_real_repo_name(path: Path) -> None:
    if path.name.startswith("15_") or path.name.startswith("01_"):
        raise ValueError("numero da pasta gerencial nao pode fazer parte do nome do repositorio real")
    if " " in path.name:
        raise ValueError("nome do repositorio real deve ser slug sem espacos")


def central_project_folder_name(project_root: Path, ordinal: int = 15) -> str:
    assert_real_repo_name(project_root)
    if project_root.name == "tudo-para-ia-mais-humana":
        return f"{ordinal:02d}_repo_tudo-para-ia-mais-humana-platform"
    return f"{ordinal:02d}_repo_{project_root.name}"


def expected_remote_url(repo_name: str) -> str:
    if repo_name.startswith("http://") or repo_name.startswith("https://"):
        return repo_name
    clean = repo_name.strip().removeprefix("admin/")
    return f"https://git.ami.app.br/admin/{clean}.git"


def platform_relative(path: Path, base: Path) -> str:
    try:
        return str(path.relative_to(base)).replace("\\", "/")
    except ValueError:
        return str(path).replace("\\", "/")


def describe_paths(paths: PlatformPaths) -> tuple[str, ...]:
    return (
        f"ecosystem_root={paths.ecosystem_root}",
        f"project_root={paths.project_root}",
        f"central_folder={paths.central_folder}",
        f"sqlite_path={paths.sqlite_path}",
        f"reports_dir={paths.reports_dir}",
        f"orders_executive_dir={paths.orders_executive_dir}",
        f"orders_managerial_dir={paths.orders_managerial_dir}",
    )


def path_health(paths: PlatformPaths) -> dict[str, bool]:
    return {
        "ecosystem_root_exists": paths.ecosystem_root.exists(),
        "project_root_exists": paths.project_root.exists(),
        "central_folder_exists": paths.central_folder.exists(),
        "sqlite_parent_exists": paths.sqlite_path.parent.exists(),
        "reports_dir_exists": paths.reports_dir.exists(),
        "orders_executive_dir_exists": paths.orders_executive_dir.exists(),
        "orders_managerial_dir_exists": paths.orders_managerial_dir.exists(),
    }


def path_health_markdown(paths: PlatformPaths) -> str:
    lines = ["# Path Health Mais Humana", ""]
    for key, value in path_health(paths).items():
        lines.append(f"- {key}: `{value}`")
    lines.append("")
    lines.append("## Caminhos")
    lines.append("")
    for line in describe_paths(paths):
        lines.append(f"- `{line}`")
    return "\n".join(lines) + "\n"


def missing_required_paths(paths: PlatformPaths) -> tuple[str, ...]:
    health = path_health(paths)
    return tuple(key for key, exists in health.items() if not exists)


def path_ready(paths: PlatformPaths) -> bool:
    return not missing_required_paths(paths)


def path_action_hint(paths: PlatformPaths) -> str:
    missing = missing_required_paths(paths)
    if not missing:
        return "caminhos essenciais prontos"
    return "criar ou validar: " + ", ".join(missing)
