"""Deny-by-default routing contract for SHIRE Blender specialist profiles."""

from __future__ import annotations

import copy
import re


SCHEMA = "shire.blender_brain.route.v1"
FAST_MODEL = "shire-blender-fast:qwen3-1.7b"
DEEP_MODEL = "shire-blender-deep:qwen3-8b"

ROUTES = {
    "questions": {"model": FAST_MODEL, "max_tokens": 384},
    "summary": {"model": FAST_MODEL, "max_tokens": 320},
    "validation_report": {"model": FAST_MODEL, "max_tokens": 512},
    "design_brief": {"model": DEEP_MODEL, "max_tokens": 640},
    "concept_spec": {"model": DEEP_MODEL, "max_tokens": 640},
    "modelling_plan": {"model": DEEP_MODEL, "max_tokens": 700},
    "script_draft": {"model": DEEP_MODEL, "max_tokens": 700},
    "recovery_plan": {"model": DEEP_MODEL, "max_tokens": 512},
}

DENIED_CAPABILITIES = {
    "automatic_retry_allowed": False,
    "blender_execution_allowed": False,
    "blender_mcp_allowed": False,
    "export_allowed": False,
    "model_install_allowed": False,
    "rendering_allowed": False,
    "script_execution_allowed": False,
    "xp_grants_authority": False,
}

PROJECT_ID_RE = re.compile(r"^BMP-[0-9]{4,}$")
SHA256_RE = re.compile(r"^[0-9a-f]{64}$")


class BlenderBrainContractError(ValueError):
    """Raised when a specialist request violates the locked contract."""


def prepare_route(
    task: str,
    project_id: str,
    revision: int,
    artifact_sha256: str,
) -> dict:
    """Return a deterministic, non-executing specialist routing manifest."""
    task = str(task).strip().lower()
    if task not in ROUTES:
        raise BlenderBrainContractError("unsupported Blender Brain task")
    if not PROJECT_ID_RE.fullmatch(str(project_id).strip()):
        raise BlenderBrainContractError("invalid Blender Mastery project identifier")
    if isinstance(revision, bool) or not isinstance(revision, int) or revision < 1:
        raise BlenderBrainContractError("revision must be a positive integer")
    digest = str(artifact_sha256).strip().lower()
    if not SHA256_RE.fullmatch(digest):
        raise BlenderBrainContractError("artifact SHA-256 must be lowercase hexadecimal")

    route = ROUTES[task]
    return {
        "schema": SCHEMA,
        "authority_effect": "NONE_DRAFT_ONLY",
        "task": task,
        "project_id": str(project_id).strip(),
        "revision": revision,
        "artifact_sha256": digest,
        "model": route["model"],
        "max_tokens": route["max_tokens"],
        "capabilities": copy.deepcopy(DENIED_CAPABILITIES),
        "sequential_execution_required": True,
    }

