# -*- coding: utf-8 -*-
"""Project-level Server Manager config directory helpers."""

from .shared import *


def get_server_manager_config_dir(server_root: Union[str, Path]) -> Path:
    """Tool-managed project config directory: <project>/.server_manager/config."""
    return Path(server_root).resolve() / '.server_manager' / 'config'


def get_bundled_tool_config_template_dir() -> Path:
    """Bundled config template directory."""
    if getattr(sys, 'frozen', False):
        return Path(sys.executable).resolve().parent / 'config'
    return Path(__file__).resolve().parents[3] / 'resources' / 'config'


def get_default_config_path(project_root: Union[str, Path]) -> Path:
    return get_server_manager_config_dir(project_root) / DEFAULT_CONFIG_FILE


def get_legacy_default_config_path(project_root: Union[str, Path]) -> Path:
    return get_server_manager_config_dir(project_root) / LEGACY_DEFAULT_CONFIG_FILE


def get_user_config_path(project_root: Union[str, Path]) -> Path:
    return get_server_manager_config_dir(project_root) / USER_CONFIG_FILE


def get_legacy_user_config_path(project_root: Union[str, Path]) -> Path:
    return get_server_manager_config_dir(project_root) / LEGACY_USER_CONFIG_FILE


def get_project_config_path(project_root: Union[str, Path]) -> Path:
    return Path(project_root).resolve() / 'config' / PROJECT_CONFIG_FILE


def _first_existing(paths: Tuple[Path, ...]) -> Optional[Path]:
    return next((path for path in paths if path.exists()), None)


def find_existing_default_config_path(project_root: Union[str, Path]) -> Optional[Path]:
    return _first_existing((
        get_default_config_path(project_root),
        get_legacy_default_config_path(project_root),
    ))


def find_existing_user_config_path(project_root: Union[str, Path]) -> Optional[Path]:
    return _first_existing((
        get_user_config_path(project_root),
        get_legacy_user_config_path(project_root),
    ))


def _migrate_legacy_config_names(project_root: Path) -> None:
    """Move legacy project config names to the current names when possible."""
    cfg = get_server_manager_config_dir(project_root)
    renames = (
        (cfg / LEGACY_USER_CONFIG_FILE, cfg / USER_CONFIG_FILE),
        (cfg / LEGACY_DEFAULT_CONFIG_FILE, cfg / DEFAULT_CONFIG_FILE),
    )
    for old_path, new_path in renames:
        if old_path.exists() and not new_path.exists():
            try:
                shutil.move(str(old_path), str(new_path))
            except Exception:
                pass


def sync_server_manager_config_templates(project_root: Path) -> Tuple[bool, str]:
    """Sync bundled managed template files into <project>/.server_manager/config."""
    project_root = Path(project_root).resolve()
    src = get_bundled_tool_config_template_dir()
    dst = get_server_manager_config_dir(project_root)

    if not src.is_dir():
        return False, (
            f'Cannot find bundled config template directory: {src}\n'
            'Please make sure the install directory or resources/config is complete.'
        )
    default_src = src / DEFAULT_CONFIG_FILE
    if not default_src.exists():
        legacy_default_src = src / LEGACY_DEFAULT_CONFIG_FILE
        default_src = legacy_default_src if legacy_default_src.exists() else default_src
    if not default_src.exists():
        return False, (
            f'Bundled config templates are incomplete; missing {DEFAULT_CONFIG_FILE}: {src}'
        )

    try:
        dst.mkdir(parents=True, exist_ok=True)
        _migrate_legacy_config_names(project_root)
        for file_name in MANAGED_CONFIG_TEMPLATE_FILES:
            src_file = default_src if file_name == DEFAULT_CONFIG_FILE else src / file_name
            if not src_file.exists():
                return False, f'Bundled config templates are incomplete; missing {file_name}: {src}'
            dst_file = dst / file_name
            if file_name == DEFAULT_CONFIG_FILE and dst_file.exists():
                continue
            shutil.copy2(src_file, dst_file)
    except Exception as e:
        return False, f'Failed to sync config templates into project: {e}'

    return True, ""


def ensure_server_manager_config(project_root: Path) -> Tuple[bool, str]:
    """Ensure .server_manager/config exists and bundled templates have been synced."""
    project_root = Path(project_root).resolve()
    sm = get_server_manager_config_dir(project_root)

    try:
        if not sm.is_dir():
            (project_root / '.server_manager').mkdir(parents=True, exist_ok=True)
    except Exception as e:
        return False, f'Failed to create project config directory: {e}'

    return sync_server_manager_config_templates(project_root)


def ensure_and_get_server_manager_config_dir(project_root: Path) -> Tuple[Optional[Path], str]:
    """Ensure the tool config directory exists and contains default.config."""
    ok, err = ensure_server_manager_config(project_root)
    if not ok:
        return None, err
    cfg = get_server_manager_config_dir(project_root)
    if not (cfg / DEFAULT_CONFIG_FILE).exists():
        return None, (
            f'Project config is incomplete: .server_manager/config is missing {DEFAULT_CONFIG_FILE}'
        )
    return cfg, ""


def project_has_default_kv_for_manager(project_root: Union[str, Path]) -> bool:
    """Backward-compatible project validity check used by recent-project lists."""
    p = Path(project_root)
    return (
        (get_server_manager_config_dir(p) / DEFAULT_CONFIG_FILE).exists()
        or (get_server_manager_config_dir(p) / LEGACY_DEFAULT_CONFIG_FILE).exists()
        or (p / 'config' / PROJECT_CONFIG_FILE).exists()
        or (p / 'config' / DEFAULT_CONFIG_FILE).exists()
        or (p / 'config' / LEGACY_DEFAULT_CONFIG_FILE).exists()
    )
