"""The M0/M1 acceptance artifact: a castle room built from primitives.

Deliberately NOT a torture test of Blender -- it is a torture test of the LOOP.
It exercises the things a real composition step needs (booleans, arrays,
materials, instancing, transforms) and produces something a human can judge in
one glance: either the contact sheet shows a castle room, or it does not.
"""

import math

import bpy

ROOM = 12.0
WALL_H = 5.0
WALL_T = 0.6


def _clear():
    bpy.ops.wm.read_factory_settings(use_empty=True)


def _mat(name, rgb, rough=0.85):
    m = bpy.data.materials.new(name)
    m.use_nodes = True
    bsdf = m.node_tree.nodes["Principled BSDF"]
    bsdf.inputs["Base Color"].default_value = (*rgb, 1.0)
    # 'Roughness' is stable across 4.x; 'Specular' was RENAMED in 4.0 and is the
    # single most common KeyError in LLM-written bpy. Do not reach for it.
    bsdf.inputs["Roughness"].default_value = rough
    # BOTH, and the second one is the trap: Workbench's MATERIAL colour mode --
    # what every contact sheet renders -- reads `diffuse_color`, NOT the
    # Principled BSDF. Setting only the BSDF gives a scene that exports with
    # correct colours, reports materialCount>0, and renders ENTIRELY GREY.
    # Numbers cannot catch this; the picture can. Measured 2026-08-31.
    m.diffuse_color = (*rgb, 1.0)
    return m


def _cube(name, loc, scale, mat):
    bpy.ops.mesh.primitive_cube_add(size=2.0, location=loc)
    o = bpy.context.active_object
    o.name = name
    o.scale = scale
    o.data.materials.append(mat)
    return o


def build():
    _clear()
    stone = _mat("Stone", (0.46, 0.44, 0.41))
    dark = _mat("StoneDark", (0.26, 0.25, 0.24))
    wood = _mat("Wood", (0.24, 0.14, 0.07))
    roofm = _mat("Roof", (0.35, 0.12, 0.12), rough=0.6)
    fire = _mat("Fire", (1.0, 0.45, 0.1), rough=0.4)

    _cube("Floor", (0, 0, -0.25), (ROOM / 2, ROOM / 2, 0.25), dark)

    half = ROOM / 2
    # Three solid walls; the south wall is split to leave a doorway.
    _cube("Wall_N", (0, half, WALL_H / 2), (half, WALL_T / 2, WALL_H / 2), stone)
    _cube("Wall_E", (half, 0, WALL_H / 2), (WALL_T / 2, half, WALL_H / 2), stone)
    _cube("Wall_W", (-half, 0, WALL_H / 2), (WALL_T / 2, half, WALL_H / 2), stone)
    door = 2.2
    side = (ROOM - door) / 4
    for sgn in (-1, 1):
        _cube(f"Wall_S{'L' if sgn < 0 else 'R'}",
              (sgn * (door / 2 + side), -half, WALL_H / 2),
              (side, WALL_T / 2, WALL_H / 2), stone)
    _cube("Lintel", (0, -half, WALL_H - 0.5), (door / 2, WALL_T / 2, 0.5), stone)

    # Crenellations: a real array, not four hand-placed boxes.
    for i in range(9):
        x = -half + 0.6 + i * (ROOM - 1.2) / 8
        for y in (half, -half):
            _cube(f"Cren_{i}_{'n' if y > 0 else 's'}",
                  (x, y, WALL_H + 0.35), (0.35, WALL_T / 2, 0.35), stone)

    # Corner towers with conical roofs.
    for i, (sx, sy) in enumerate(((1, 1), (1, -1), (-1, 1), (-1, -1))):
        cx, cy = sx * half, sy * half
        bpy.ops.mesh.primitive_cylinder_add(radius=1.5, depth=WALL_H + 2.0,
                                            location=(cx, cy, (WALL_H + 2.0) / 2), vertices=16)
        t = bpy.context.active_object
        t.name = f"Tower_{i}"
        t.data.materials.append(stone)
        bpy.ops.mesh.primitive_cone_add(radius1=2.0, depth=2.4, vertices=16,
                                        location=(cx, cy, WALL_H + 2.0 + 1.2))
        r = bpy.context.active_object
        r.name = f"TowerRoof_{i}"
        r.data.materials.append(roofm)

    # A table, so the room reads as inhabited and the sheet has a scale cue.
    _cube("TableTop", (0, 1.0, 1.1), (2.2, 0.9, 0.12), wood)
    for dx in (-1.9, 1.9):
        for dy in (-0.65, 0.65):
            _cube(f"Leg_{dx}_{dy}", (dx, 1.0 + dy, 0.55), (0.12, 0.12, 0.55), wood)

    # Wall torches -- emissive-ish spheres; they also prove material assignment.
    for i, (tx, ty) in enumerate(((-half + 0.6, 2.5), (-half + 0.6, -2.5),
                                  (half - 0.6, 2.5), (half - 0.6, -2.5))):
        _cube(f"Sconce_{i}", (tx, ty, 3.0), (0.15, 0.15, 0.4), wood)
        bpy.ops.mesh.primitive_uv_sphere_add(radius=0.32, location=(tx, ty, 3.5), segments=12, ring_count=8)
        f = bpy.context.active_object
        f.name = f"Flame_{i}"
        f.data.materials.append(fire)

    bpy.ops.object.select_all(action="DESELECT")
    n = len(bpy.context.scene.objects)
    tris = sum(
        sum(max(len(p.vertices) - 2, 0) for p in o.data.polygons)
        for o in bpy.context.scene.objects if o.type == "MESH"
    )
    print(f"castle: {n} objects, {tris} tris")
    return n, tris


build()
