from __future__ import annotations

from importlib import metadata
from pathlib import Path
from typing import Mapping, Optional, Tuple, List

from . import __version__
from .commands import COMMANDS, build_env, resolve_script_path
from .runtime import (
    data_root_from_env,
    ensure_runtime,
    find_work_repo,
    packaged_manifest,
    runtime_current_dir,
    runtime_is_current,
    sha256_path,
)


def package_version() -> str:
    try:
        return metadata.version("lehome")
    except metadata.PackageNotFoundError:
        return __version__


def _source_truth_status(env: Mapping[str, str], manifest: dict) -> Tuple[Path, str, List[str]]:
    source_root = Path(env.get("LEHOME_CLI_SOURCE", "/root/data/lehome_cli")).expanduser()
    if not source_root.exists():
        return source_root, "unavailable", []

    mismatches: list[str] = []
    for entry in manifest.get("files", []):
        source_path = source_root / entry["source_relpath"]
        if not source_path.is_file():
            mismatches.append(f"missing:{entry['source_relpath']}")
            continue
        if sha256_path(source_path) != entry["sha256"]:
            mismatches.append(entry["source_relpath"])

    return source_root, ("ok" if not mismatches else "mismatch"), mismatches


def format_version_report() -> str:
    manifest = packaged_manifest()
    lines = [
        f"package_version: {package_version()}",
        f"bundle_version: {manifest.get('bundle_version', 'unknown')}",
        f"imported_at: {manifest.get('imported_at', 'unknown')}",
    ]
    return "\n".join(lines)


def format_doctor_report() -> str:
    env = build_env()
    manifest = packaged_manifest()
    runtime_dir = ensure_runtime(env)
    work_repo = find_work_repo(env)
    source_root, source_status, mismatches = _source_truth_status(env, manifest)

    lines = [
        "LeHome CLI Doctor",
        f"package_version: {package_version()}",
        f"bundle_version: {manifest.get('bundle_version', 'unknown')}",
        f"imported_at: {manifest.get('imported_at', 'unknown')}",
        f"data_root: {data_root_from_env(env)}",
        f"runtime_dir: {runtime_dir}",
        f"runtime_current: {'yes' if runtime_is_current(env) else 'no'}",
        f"work_repo: {work_repo if work_repo else '<missing>'}",
        f"source_root: {source_root}",
        f"source_sync: {source_status}",
    ]

    if mismatches:
        lines.append("source_mismatches:")
        for item in mismatches:
            lines.append(f"  - {item}")

    lines.append("command_targets:")
    for name in COMMANDS:
        lines.append(f"  - {name}: {resolve_script_path(name, runtime_dir)}")

    return "\n".join(lines)
