from __future__ import annotations

import hashlib
import json

from app.core.orchestration.agent.schemas import (
    validate_model_plan,
    validate_planning_request,
)
from app.core.orchestration.spec import workflow_spec_hash


def evaluate_model_plan(plan, request):
    if request.get("target_conflicts"):
        raise ValueError("conflicting target ownership requires a safe rejection")
    return validate_model_plan(
        plan,
        dataflow_uid=request["dataflow_uid"],
        authorized_resources=request["authorized_resources"],
    )


def _hash(value):
    canonical = json.dumps(
        value,
        sort_keys=True,
        separators=(",", ":"),
        ensure_ascii=False,
    )
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def replay_candidate_plan(candidate_plan, planning_request):
    request = validate_planning_request(planning_request)
    plan = evaluate_model_plan(candidate_plan, request)
    return {
        "allowed": True,
        "schema_version": "v54",
        "context_hash": _hash(request),
        "candidate_hash": _hash(plan),
        "workflow_hash": workflow_spec_hash(plan["workflow_spec"]),
        "schedule_hash": _hash(plan["schedule_plan"]),
        "decision_summary": plan["decision_summary"],
    }
