from __future__ import annotations

from pathlib import Path
from typing import Any

from .source import SourcePackage
from .util import load_json, utc_now, write_json
from .validation import validate_page


def stage_agent_review(
    *,
    reviewed_path: Path,
    source: SourcePackage,
    reviewer: str,
    notes: list[str],
    golden_path: Path,
    edition_path: Path,
) -> dict[str, Any]:
    page = load_json(reviewed_path)
    if page["review"]["status"] == "owner_approved":
        raise ValueError("Agent workflow cannot create or modify owner-approved status")
    timestamp = utc_now()
    page["review"] = {
        "status": "agent_reviewed",
        "authority": "diagnostic_only",
        "reviewer": reviewer,
        "reviewed_at": timestamp,
        "notes": [
            "Diagnostic fixture only; it is not independent ground truth and has not been owner-approved.",
            *notes,
        ],
    }
    page["provenance"]["steps"].append(
        {
            "kind": "agent_review",
            "actor": reviewer,
            "artifact": str(reviewed_path),
            "created_at": timestamp,
        }
    )
    report = validate_page(page, source)
    if not report.valid:
        raise ValueError("Reviewed page failed validation:\n" + "\n".join(report.errors))
    write_json(golden_path, page)
    write_json(edition_path, page)
    return page

