"""
Shared EMDS workspace/bootstrap path helpers.
"""

from __future__ import annotations

import os
from dataclasses import dataclass
from pathlib import Path

from .qt_compat import QStandardPaths


# Naming history: prior to the YYYY.MM rebrand the folder was called
# "EmdsProjects9" (the "9" was a legacy semver tie-in). Starting with
# 2026.05 it's "EmdsProjects" — no version number embedded in the path.
# Kept in lockstep with the ArcGIS Pro add-in.
EMDS_PROJECTS_FOLDER_NAME = "EmdsProjects"
EMDS_MASTER_DB_NAME = "emdsInfo.sqlite"

# Legacy folder name retained so a one-shot migration on first launch
# can detect and rename an existing install. New installs never see it.
EMDS_PROJECTS_FOLDER_NAME_LEGACY = "EmdsProjects9"


@dataclass(frozen=True)
class EMDSWorkspacePaths:
    documents_dir: Path
    projects_dir: Path
    metadata_db_path: Path


def _resolve_documents_directory() -> Path:
    """Resolve the user's Documents-equivalent folder with Qt-aware fallbacks."""
    location = ""
    try:
        documents_location = getattr(QStandardPaths, "DocumentsLocation", None)
        if documents_location is None and hasattr(QStandardPaths, "StandardLocation"):
            documents_location = QStandardPaths.StandardLocation.DocumentsLocation
        if documents_location is not None:
            location = QStandardPaths.writableLocation(documents_location) or ""
    except Exception:
        location = ""

    candidates = []
    if location:
        candidates.append(Path(location))
    candidates.append(Path.home() / "Documents")

    for candidate in candidates:
        candidate = candidate.expanduser()
        if candidate.exists():
            return candidate

    return candidates[0].expanduser()


def resolve_workspace_paths() -> EMDSWorkspacePaths:
    documents_dir = _resolve_documents_directory()
    projects_dir = documents_dir / EMDS_PROJECTS_FOLDER_NAME
    metadata_db_path = projects_dir / EMDS_MASTER_DB_NAME
    return EMDSWorkspacePaths(
        documents_dir=documents_dir,
        projects_dir=projects_dir,
        metadata_db_path=metadata_db_path,
    )


def ensure_workspace() -> EMDSWorkspacePaths:
    """Create the shared EMDS workspace and expose its DB path via env var."""
    paths = resolve_workspace_paths()
    paths.projects_dir.mkdir(parents=True, exist_ok=True)
    os.environ["EMDS_METADATA_DB_PATH"] = str(paths.metadata_db_path)
    return paths
