from __future__ import annotations

from pathlib import Path

import yaml
from pydantic import ValidationError

from one_run.compat import warn_legacy_manifest
from one_run.errors import ManifestError
from one_run.models import Manifest


def load_manifest(path: str | Path) -> Manifest:
    manifest_path = Path(path)
    if not manifest_path.exists():
        raise ManifestError(f"manifest not found: {manifest_path}")

    try:
        payload = yaml.safe_load(manifest_path.read_text(encoding="utf-8"))
    except yaml.YAMLError as exc:
        raise ManifestError(f"invalid yaml in {manifest_path}: {exc}") from exc

    if payload is None:
        raise ManifestError(f"manifest is empty: {manifest_path}")

    warn_legacy_manifest(payload, manifest_path)

    try:
        return Manifest.model_validate(payload)
    except ValidationError as exc:
        raise ManifestError(f"manifest validation failed for {manifest_path}:\n{exc}") from exc
