"""Provider-registry-derived worker artifact paths."""
from __future__ import annotations

from pathlib import Path
from typing import Any, Mapping

from .models import provider_ids


def artifact_worker_ids() -> list[str]:
    """All analysis worker ids plus the non-analysis report writer slot."""
    return [*provider_ids("analyser"), "report-writer"]


def artifacts_from_context(
    ctx: Mapping[str, Any], *, relative: bool
) -> dict[str, dict[str, str]]:
    """Derive prompt/result/error paths without provider-specific branches."""
    prompt_root = _context_root(ctx, "RUN_PROMPTS", relative)
    result_root = _context_root(ctx, "WORKER_RESULTS", relative)
    task_type = str(ctx.get("TASK_TYPE_SEGMENT", ""))
    prompt_suffix = f"-{task_type}-{ctx.get('RUN_PROMPTS_SEQ', '')}"
    result_suffix = f"-{task_type}-{ctx.get('WORKER_RESULTS_SEQ', '')}"
    return {
        worker_id: {
            "promptPath": str(prompt_root / f"{worker_id}-worker-prompt{prompt_suffix}.md"),
            "resultPath": str(result_root / f"{worker_id}-worker{result_suffix}.md"),
            "errorsSidecarPath": str(
                result_root / f"{worker_id}-worker-errors{result_suffix}.json"
            ),
        }
        for worker_id in artifact_worker_ids()
    }


def _context_root(ctx: Mapping[str, Any], name: str, relative: bool) -> Path:
    if name == "WORKER_RESULTS":
        key = "WORKER_RESULTS_RELATIVE_PATH" if relative else "WORKER_RESULTS_PATH"
    else:
        suffix = "RELATIVE_PATH" if relative else "DIR"
        key = f"{name}_{suffix}"
    value = str(ctx.get(key, ""))
    if value or relative:
        return Path(value)
    relative_value = str(ctx.get(f"{name}_RELATIVE_PATH", ""))
    return Path(str(ctx.get("PROJECT_ROOT", ""))) / relative_value
