from pathlib import Path

import trimesh

from flexiforge.shire_bridge import ShireJobStore


def test_approval_gated_shire_workflow(tmp_path: Path, monkeypatch):
    models = tmp_path / "models"
    jobs = tmp_path / "jobs"
    exports = tmp_path / "exports"
    vault = tmp_path / "vault"
    models.mkdir()
    vault.mkdir()
    monkeypatch.setenv("FLEXIFORGE_ALLOW_UNMOUNTED_VAULT", "1")

    model_id = "test-model"
    mesh = trimesh.creation.box(extents=[80, 24, 16])
    mesh.export(models / f"{model_id}.stl")

    store = ShireJobStore(jobs, models, exports)
    job = store.create_job(model_id, "Dragon Fidget", "Articulate the tail", "wiggle", 0.35, 5)
    assert job["state"] == "AWAITING_DESIGN_SELECTION"
    assert job["suggestions"]

    selected = store.select_suggestion(job["job_id"], job["suggestions"][0]["suggestion_id"], "hinge")
    assert selected["state"] == "AWAITING_DESIGN_APPROVAL"

    design_token = store.approval_token(job["job_id"], "design")
    approved = store.approve(job["job_id"], "design", design_token)
    assert approved["state"] == "APPROVED_FOR_FORGE"

    forged = store.forge(job["job_id"])
    assert forged["state"] == "FORGED"
    validated = store.validate(job["job_id"])
    assert validated["state"] == "VALIDATED"

    export_token = store.approval_token(job["job_id"], "export")
    export_approved = store.approve(job["job_id"], "export", export_token)
    assert export_approved["state"] == "APPROVED_FOR_EXPORT"

    exported = store.export_to_vault(job["job_id"], vault)
    assert exported["state"] == "EXPORTED"
    destination = Path(exported["export"]["destination"])
    assert destination.exists()
    assert (destination / "SHIRE_FlexiForge_Manifest.json").exists()
