"""Workspace detection and path resolution for HatchDX projects."""

from __future__ import annotations

from pathlib import Path

WORKSPACE_MARKER = "hdx-workspace.toml"


def find_workspace(start: Path | None = None) -> Path | None:
    """Walk up from *start* (default: CWD) looking for hdx-workspace.toml.

    Returns the directory containing the marker, or None if not found.
    """
    current = (start or Path.cwd()).resolve()

    for parent in [current, *current.parents]:
        if (parent / WORKSPACE_MARKER).is_file():
            return parent
    return None


def discover_servers(root: Path) -> list[Path]:
    """Return sorted list of server project directories under *root*/servers/.

    A directory qualifies as a server project if it contains
    ``pyproject.toml`` or ``hdx.toml``.
    """
    servers_dir = root / "servers"
    if not servers_dir.is_dir():
        return []

    results: list[Path] = []
    for child in sorted(servers_dir.iterdir()):
        if not child.is_dir():
            continue
        if (child / "pyproject.toml").is_file() or (child / "hdx.toml").is_file():
            results.append(child)
    return results


def discover_server_eval_dbs(root: Path) -> list[Path]:
    """Return list of existing server eval DB paths across the workspace."""
    dbs: list[Path] = []
    for server_dir in discover_servers(root):
        db_path = server_dir / ".hdx" / "eval_results.db"
        if db_path.is_file():
            dbs.append(db_path)
    return dbs


def detect_output_dir(entity_type: str) -> Path:
    """Return the appropriate output directory for a server or agent.

    If inside a workspace, returns ``workspace/servers/`` or ``workspace/agents/``.
    Otherwise returns CWD.
    """
    workspace = find_workspace()
    if workspace is None:
        return Path.cwd()

    if entity_type == "server":
        target = workspace / "servers"
    elif entity_type == "agent":
        target = workspace / "agents"
    else:
        return Path.cwd()

    target.mkdir(exist_ok=True)
    return target
