"""Shared helpers for tools API sub-modules."""

from typing import Any

from fastapi import HTTPException


def _get_ticket(ticket_id: str):
    """Fetch a ticket by ID. Raises 404 if not found."""
    from proxym.dashboard._tickets_api import _tickets
    mgr = _tickets()
    ticket = mgr.get_ticket(ticket_id)
    if not ticket:
        raise HTTPException(404, f"Ticket '{ticket_id}' not found")
    return ticket


def _default_project_dir(project_id: str | None = None) -> str:
    """Return project directory for dispatch."""
    if project_id:
        try:
            from proxym.dashboard._projects_api import _get_registry

            project = _get_registry().get(project_id)
            if project and project.local_path:
                return project.local_path
        except Exception:
            pass
    try:
        from proxym.config import get_settings

        s = get_settings()
        return str(getattr(s, "projects_root", "~/github"))
    except Exception:
        return "~/github"


def _job_snapshot(job) -> dict[str, Any]:
    """Return a rich job payload for dashboard views."""
    data = job.summary()
    if job.result:
        data["result"] = {
            **job.result.summary(),
            "stdout": job.result.stdout,
            "stderr": job.result.stderr,
        }
    if getattr(job, "ticket_id", None):
        try:
            data["ticket"] = _get_ticket(job.ticket_id).summary()
        except HTTPException:
            data["ticket"] = None
    return data
