from __future__ import annotations

import json
import sys

repo = sys.argv[1]
sys.path.insert(0, repo)

from ai import brain_server as brain  # noqa: E402

assert (
    brain.ACADEMY_OUTPUT_CONTRACT
    == "academy_round_json_v6"
)

assert hasattr(
    brain,
    "_academy_round1_correction_prompt",
)

valid_round1 = {
    "round": 1,
    "principles": [
        "Define a closed profile before creating an extrusion.",
        "Use explicit dimensions and units for every controlling value.",
        "Validate the resulting solid instead of assuming success.",
    ],
    "repeatable_method_steps": [
        "Create and constrain one closed two-dimensional profile.",
        "Apply a positive extrusion distance along the intended axis.",
        "Inspect the resulting solid and record measurable acceptance evidence.",
    ],
    "acceptance_criteria": [
        "The result contains exactly one valid solid body.",
        "The measured height matches the requested extrusion distance.",
    ],
    "required_inputs": [
        "Closed profile dimensions",
        "Extrusion distance",
    ],
    "safe_knowledge_gate": (
        "This is knowledge-only guidance and does not claim "
        "tool execution or physical validation."
    ),
    "limitations": [
        "No CadQuery command was executed by this contract test.",
        "No physical print or professional review was completed.",
    ],
    "forge_execution_allowed": False,
}

normalised = brain.canonicalise_academy_answer(
    json.dumps(valid_round1),
    1,
)

payload = json.loads(normalised["canonical"])

assert payload["round"] == 1
assert len(payload["principles"]) == 3
assert len(payload["repeatable_method_steps"]) == 3
assert len(payload["acceptance_criteria"]) == 2
assert 1 <= len(payload["required_inputs"]) <= 3
assert len(payload["limitations"]) == 2
assert payload["forge_execution_allowed"] is False

invalid_round1 = dict(valid_round1)
invalid_round1["repeatable_method_steps"] = [
    "Create a profile.",
    "Extrude the profile.",
]

try:
    brain.canonicalise_academy_answer(
        json.dumps(invalid_round1),
        1,
    )
except brain.AcademyStructuredOutputError:
    pass
else:
    raise AssertionError(
        "Invalid two-step Round 1 payload was accepted."
    )

correction_prompt = (
    brain._academy_round1_correction_prompt(
        "Learn safe extrusion fundamentals.",
        json.dumps(invalid_round1),
        "round 1 needs three method steps",
    )
)

assert "repeatable_method_steps" in correction_prompt
assert "exactly three" in correction_prompt
assert "forge_execution_allowed must be false" in correction_prompt
assert "no markdown" in correction_prompt.lower()

print("PASS: Live Academy contract is v6.")
print("PASS: Valid three-step Round 1 payload is accepted.")
print("PASS: Invalid two-step Round 1 payload is rejected.")
print("PASS: Corrective prompt requires exactly three steps.")
print("PASS: Forge remains explicitly prohibited.")
