import bpy
import math
import random
import os

# Set fixed seed for reproducible procedural details
random.seed(42)

def clear_scene():
    bpy.ops.object.select_all(action='SELECT')
    bpy.ops.object.delete(use_global=False)
    for block in bpy.data.meshes:
        if block.users == 0:
            bpy.data.meshes.remove(block)
    for block in bpy.data.materials:
        if block.users == 0:
            bpy.data.materials.remove(block)

def create_material(name, base_color, roughness=0.7, metallic=0.0,
                    emission_color=None, emission_strength=0.0, alpha=1.0, transmission=0.0):
    mat = bpy.data.materials.new(name=name)
    mat.use_nodes = True
    nodes = mat.node_tree.nodes
    bsdf = nodes.get("Principled BSDF")
    if bsdf:
        bsdf.inputs["Base Color"].default_value = (*base_color, 1.0)
        bsdf.inputs["Roughness"].default_value = roughness
        bsdf.inputs["Metallic"].default_value = metallic
        if alpha < 1.0 and "Alpha" in bsdf.inputs:
            bsdf.inputs["Alpha"].default_value = alpha
        if transmission > 0.0 and "Transmission Weight" in bsdf.inputs:
            bsdf.inputs["Transmission Weight"].default_value = transmission
        if emission_color and emission_strength > 0:
            if "Emission Color" in bsdf.inputs:
                bsdf.inputs["Emission Color"].default_value = (*emission_color, 1.0)
                bsdf.inputs["Emission Strength"].default_value = emission_strength
            elif "Emission" in bsdf.inputs:
                bsdf.inputs["Emission"].default_value = (*emission_color, 1.0)
    return mat

def add_bevel(obj, width=0.015, segments=2):
    mod = obj.modifiers.new(name="Bevel", type='BEVEL')
    mod.width = width
    mod.segments = segments
    mod.limit_method = 'ANGLE'

def link_to_collection(obj, collection):
    for col in obj.users_collection:
        col.objects.unlink(obj)
    collection.objects.link(obj)

def create_log(name, length, radius, location, rotation, material, collection, vertices=20):
    bpy.ops.mesh.primitive_cylinder_add(
        vertices=vertices,
        radius=radius,
        depth=length,
        location=location,
        rotation=rotation
    )
    obj = bpy.context.active_object
    obj.name = name
    obj.data.materials.append(material)
    for poly in obj.data.polygons:
        poly.use_smooth = True
    link_to_collection(obj, collection)
    return obj

def create_box(name, size, location, rotation=(0, 0, 0), material=None, collection=None, bevel=0.01):
    bpy.ops.mesh.primitive_cube_add(size=1.0, location=location, rotation=rotation)
    obj = bpy.context.active_object
    obj.name = name
    obj.scale = (size[0], size[1], size[2])
    bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
    if bevel > 0:
        add_bevel(obj, width=bevel, segments=2)
    if material:
        obj.data.materials.append(material)
    if collection:
        link_to_collection(obj, collection)
    return obj

def build_wall_segments(name_prefix, total_span, openings, fixed_coord, z_coord,
                        along_axis, log_r, material, collection):
    """
    Build log segments along X or Y axis with specified (start, end) openings cut out.
    total_span is (-half_len, +half_len).
    """
    s_min, s_max = total_span
    sorted_ops = sorted(openings, key=lambda x: x[0])
    segments = []
    cur = s_min
    for op_start, op_end in sorted_ops:
        if op_start > cur + 0.05:
            segments.append((cur, min(op_start, s_max)))
        cur = max(cur, op_end)
    if cur < s_max - 0.05:
        segments.append((cur, s_max))

    for idx, (seg_a, seg_b) in enumerate(segments):
        seg_len = seg_b - seg_a
        seg_mid = (seg_a + seg_b) / 2.0
        if along_axis == 'X':
            loc = (seg_mid, fixed_coord, z_coord)
            rot = (0, math.pi / 2, 0)
        else:
            loc = (fixed_coord, seg_mid, z_coord)
            rot = (math.pi / 2, 0, 0)
        create_log(f"{name_prefix}_Seg_{idx}", seg_len, log_r, loc, rot, material, collection)

def build_window_unit(name, center, wall_axis, width, height, mat_frame, mat_mullion, mat_glass, collection, shutters=True):
    """Build a complete window frame, cross mullions, transparent glass pane, and optional shutters."""
    cx, cy, cz = center
    frame_depth = 0.38
    frame_thick = 0.11

    if wall_axis == 'X':
        # Window sits in Front/Back wall (normal along Y)
        create_box(f"{name}_Frame_T", (width + 0.22, frame_depth, frame_thick),
                   (cx, cy, cz + height / 2.0), material=mat_frame, collection=collection)
        create_box(f"{name}_Frame_B", (width + 0.28, frame_depth + 0.06, frame_thick * 1.1),
                   (cx, cy, cz - height / 2.0), material=mat_frame, collection=collection)
        create_box(f"{name}_Frame_L", (frame_thick, frame_depth, height),
                   (cx - width / 2.0, cy, cz), material=mat_frame, collection=collection)
        create_box(f"{name}_Frame_R", (frame_thick, frame_depth, height),
                   (cx + width / 2.0, cy, cz), material=mat_frame, collection=collection)
        create_box(f"{name}_Glass", (width - 0.06, 0.03, height - 0.06),
                   (cx, cy, cz), material=mat_glass, collection=collection, bevel=0)
        create_box(f"{name}_Mullion_V", (0.045, 0.09, height - 0.06),
                   (cx, cy, cz), material=mat_mullion, collection=collection, bevel=0.004)
        create_box(f"{name}_Mullion_H", (width - 0.06, 0.09, 0.045),
                   (cx, cy, cz), material=mat_mullion, collection=collection, bevel=0.004)
        if shutters:
            out_y = cy - 0.19 if cy < 0 else cy + 0.19
            create_box(f"{name}_Shutter_L", (0.38, 0.05, height),
                       (cx - width / 2.0 - 0.26, out_y, cz), material=mat_mullion, collection=collection)
            create_box(f"{name}_Shutter_R", (0.38, 0.05, height),
                       (cx + width / 2.0 + 0.26, out_y, cz), material=mat_mullion, collection=collection)
    else:
        # Window sits in Left/Right wall (normal along X)
        create_box(f"{name}_Frame_T", (frame_depth, width + 0.22, frame_thick),
                   (cx, cy, cz + height / 2.0), material=mat_frame, collection=collection)
        create_box(f"{name}_Frame_B", (frame_depth + 0.06, width + 0.28, frame_thick * 1.1),
                   (cx, cy, cz - height / 2.0), material=mat_frame, collection=collection)
        create_box(f"{name}_Frame_F", (frame_depth, frame_thick, height),
                   (cx, cy - width / 2.0, cz), material=mat_frame, collection=collection)
        create_box(f"{name}_Frame_Bk", (frame_depth, frame_thick, height),
                   (cx, cy + width / 2.0, cz), material=mat_frame, collection=collection)
        create_box(f"{name}_Glass", (0.03, width - 0.06, height - 0.06),
                   (cx, cy, cz), material=mat_glass, collection=collection, bevel=0)
        create_box(f"{name}_Mullion_V", (0.09, 0.045, height - 0.06),
                   (cx, cy, cz), material=mat_mullion, collection=collection, bevel=0.004)
        create_box(f"{name}_Mullion_H", (0.09, width - 0.06, 0.045),
                   (cx, cy, cz), material=mat_mullion, collection=collection, bevel=0.004)
        if shutters:
            out_x = cx - 0.19 if cx < 0 else cx + 0.19
            create_box(f"{name}_Shutter_F", (0.05, 0.38, height),
                       (out_x, cy - width / 2.0 - 0.26, cz), material=mat_mullion, collection=collection)
            create_box(f"{name}_Shutter_Bk", (0.05, 0.38, height),
                       (out_x, cy + width / 2.0 + 0.26, cz), material=mat_mullion, collection=collection)

def build_interior(cabin_w, cabin_d, floor_z, wall_top_z, ridge_z, interior_col, materials):
    """Populate the enlarged cabin with rich interior furniture, loft, fireplace, kitchen, bedroom, and lighting."""
    mat_log = materials["log"]
    mat_log_dark = materials["log_dark"]
    mat_plank = materials["plank"]
    mat_floor = materials["floor"]
    mat_stone = materials["stone"]
    mat_stone_dark = materials["stone_dark"]
    mat_metal = materials["metal"]
    mat_fabric_red = materials["fabric_red"]
    mat_fabric_cream = materials["fabric_cream"]
    mat_fabric_green = materials["fabric_green"]
    mat_ember = materials["ember"]
    mat_lamp = materials["lamp"]
    mat_brass = materials["brass"]
    mat_ceramic = materials["ceramic"]

    in_w = cabin_w - 0.35
    in_d = cabin_d - 0.35

    # 1. Polished Interior Hardwood Floor Planks
    num_in_planks = 26
    pw = in_w / num_in_planks
    for i in range(num_in_planks):
        px = -in_w / 2.0 + (i + 0.5) * pw
        create_box(f"Interior_Floor_Plank_{i}", (pw * 0.96, in_d, 0.05),
                   (px, 0, floor_z + 0.04), material=mat_floor, collection=interior_col, bevel=0.004)

    # 2. Second-Floor Wooden Loft (Back half of cabin: Y from +0.6 to +cabin_d/2)
    loft_z = floor_z + 2.55
    loft_y_start = 0.65
    loft_y_end = cabin_d / 2.0 - 0.18
    loft_d = loft_y_end - loft_y_start
    loft_cy = (loft_y_start + loft_y_end) / 2.0

    # Loft main support beam & vertical posts
    create_log("Loft_Main_Beam", in_w + 0.1, 0.14, (0, loft_y_start, loft_z - 0.12),
               (0, math.pi / 2, 0), mat_log_dark, interior_col)
    for j in range(5):
        jy = loft_y_start + (j + 0.5) * (loft_d / 5.0)
        create_box(f"Loft_Joist_{j}", (in_w, 0.12, 0.16), (0, jy, loft_z - 0.08),
                   material=mat_log_dark, collection=interior_col)

    for px in [-in_w / 2.0 + 0.25, -0.85, 1.35, in_w / 2.0 - 0.25]:
        post_h = loft_z - floor_z - 0.1
        create_log(f"Loft_Support_Post_{px:.1f}", post_h, 0.11,
                   (px, loft_y_start, floor_z + post_h / 2.0), (0, 0, 0), mat_log_dark, interior_col)

    # Loft floor planks
    num_loft_planks = 24
    lpw = in_w / num_loft_planks
    for i in range(num_loft_planks):
        px = -in_w / 2.0 + (i + 0.5) * lpw
        create_box(f"Loft_Plank_{i}", (lpw * 0.95, loft_d, 0.055),
                   (px, loft_cy, loft_z + 0.03), material=mat_plank, collection=interior_col, bevel=0.004)

    # Loft railing (leaving opening on left-center x in [-1.85, -0.85] for stairs)
    rail_segments = [(-in_w / 2.0 + 0.2, -1.85, "Left"), (-0.85, in_w / 2.0 - 0.2, "Right")]
    for rx1, rx2, rname in rail_segments:
        rlen = rx2 - rx1
        rcx = (rx1 + rx2) / 2.0
        create_log(f"Loft_Rail_Top_{rname}", rlen, 0.05, (rcx, loft_y_start, loft_z + 0.92),
                   (0, math.pi / 2, 0), mat_log_dark, interior_col)
        create_log(f"Loft_Rail_Bot_{rname}", rlen, 0.04, (rcx, loft_y_start, loft_z + 0.22),
                   (0, math.pi / 2, 0), mat_log_dark, interior_col)
        nb = max(2, int(rlen / 0.28))
        for b in range(nb):
            bx = rx1 + (b + 0.5) * (rlen / nb)
            create_log(f"Loft_Baluster_{rname}_{b}", 0.68, 0.025,
                       (bx, loft_y_start, loft_z + 0.56), (0, 0, 0), mat_plank, interior_col)

    # 3. Wooden Staircase up to the Loft (along X = -1.35, from Y = -1.75 up to Y = +0.65)
    stair_x = -1.35
    stair_w = 0.88
    stair_y0 = -1.75
    stair_y1 = loft_y_start
    num_steps = 10
    for s in range(num_steps):
        frac = (s + 0.5) / num_steps
        sy = stair_y0 + frac * (stair_y1 - stair_y0)
        sz = floor_z + 0.08 + frac * (loft_z - floor_z)
        create_box(f"Stair_Tread_{s}", (stair_w, 0.26, 0.055),
                   (stair_x, sy, sz), material=mat_plank, collection=interior_col, bevel=0.008)

    # Stair stringers & handrail
    stair_dx = stair_y1 - stair_y0
    stair_dz = loft_z - floor_z
    stair_len = math.hypot(stair_dx, stair_dz)
    stair_angle = math.atan2(stair_dz, stair_dx)
    for side_s in [-1, 1]:
        sx = stair_x + side_s * (stair_w / 2.0 + 0.04)
        create_box(f"Stair_Stringer_{side_s}", (0.07, stair_len, 0.22),
                   (sx, (stair_y0 + stair_y1) / 2.0, (floor_z + loft_z) / 2.0),
                   rotation=(stair_angle, 0, 0), material=mat_log_dark, collection=interior_col)
        create_log(f"Stair_Handrail_{side_s}", stair_len + 0.2, 0.038,
                   (sx, (stair_y0 + stair_y1) / 2.0, (floor_z + loft_z) / 2.0 + 0.82),
                   (math.pi / 2 + stair_angle, 0, 0), mat_log_dark, interior_col)
        # Vertical handrail posts at bottom and top of stairs
        create_log(f"Stair_Newel_Bot_{side_s}", 0.88, 0.042,
                   (sx, stair_y0 + 0.08, floor_z + 0.44), (0, 0, 0), mat_log_dark, interior_col)
        create_log(f"Stair_Newel_Top_{side_s}", 0.88, 0.042,
                   (sx, stair_y1 - 0.05, loft_z + 0.44), (0, 0, 0), mat_log_dark, interior_col)

    # 4. Interior Stone Fireplace & Glowing Hearth (Right Wall: X = +cabin_w/2)
    fp_x = cabin_w / 2.0 - 0.52
    fp_y = -0.35
    # Raised stone hearth slab
    create_box("Hearth_Slab", (1.25, 2.1, 0.18), (fp_x - 0.22, fp_y, floor_z + 0.12),
               material=mat_stone_dark, collection=interior_col, bevel=0.025)
    # Left & Right stone pillars of firebox
    create_box("Firebox_Pillar_F", (0.85, 0.48, 1.55), (fp_x, fp_y - 0.68, floor_z + 0.88),
               material=mat_stone, collection=interior_col, bevel=0.03)
    create_box("Firebox_Pillar_B", (0.85, 0.48, 1.55), (fp_x, fp_y + 0.68, floor_z + 0.88),
               material=mat_stone, collection=interior_col, bevel=0.03)
    # Back wall & upper hood of fireplace
    create_box("Firebox_Back", (0.35, 1.4, 1.55), (fp_x + 0.26, fp_y, floor_z + 0.88),
               material=mat_stone_dark, collection=interior_col, bevel=0.02)
    create_box("Fireplace_Upper_Breast", (0.72, 1.75, 3.6), (fp_x + 0.06, fp_y, floor_z + 3.45),
               material=mat_stone, collection=interior_col, bevel=0.03)
    # Heavy Timber Mantelpiece Shelf
    create_box("Fireplace_Mantel", (0.98, 2.05, 0.16), (fp_x - 0.05, fp_y, floor_z + 1.72),
               material=mat_log_dark, collection=interior_col, bevel=0.015)

    # Firewood & glowing embers inside the firebox
    for f_i in range(4):
        create_log(f"Hearth_Log_{f_i}", 0.72, 0.075,
                   (fp_x - 0.05 + (f_i % 2) * 0.1, fp_y + (f_i - 1.5) * 0.08, floor_z + 0.28 + (f_i % 2) * 0.09),
                   (math.pi / 2 + 0.15 * (f_i - 1.5), 0, 0.2), mat_log_dark, interior_col)
    for e_i in range(5):
        create_box(f"Fire_Ember_{e_i}", (0.16, 0.22, 0.12),
                   (fp_x - 0.05, fp_y - 0.24 + e_i * 0.12, floor_z + 0.24 + (e_i % 2) * 0.06),
                   rotation=(0.3 * e_i, 0.2 * e_i, 0.4 * e_i),
                   material=mat_ember, collection=interior_col, bevel=0.03)

    # Warm Fireplace Point Light
    bpy.ops.object.light_add(type='POINT', location=(fp_x - 0.35, fp_y, floor_z + 0.55))
    fp_light = bpy.context.active_object
    fp_light.name = "Fireplace_Glow_Light"
    fp_light.data.energy = 260.0
    fp_light.data.color = (1.0, 0.48, 0.14)
    fp_light.data.shadow_soft_size = 0.35
    link_to_collection(fp_light, interior_col)

    # 5. Living Area: Woven Rug, Cozy Sofa, Coffee Table (Front-Right / Center facing Fireplace)
    rug_x, rug_y = 0.95, -0.55
    create_box("Living_Rug_Border", (2.35, 2.85, 0.02), (rug_x, rug_y, floor_z + 0.07),
               material=mat_fabric_red, collection=interior_col, bevel=0.005)
    create_box("Living_Rug_Inner", (1.95, 2.45, 0.024), (rug_x, rug_y, floor_z + 0.074),
               material=mat_fabric_cream, collection=interior_col, bevel=0.005)

    # Sofa facing the fireplace (+X)
    sofa_x, sofa_y = 0.05, -0.55
    create_box("Sofa_Base", (0.92, 2.05, 0.28), (sofa_x, sofa_y, floor_z + 0.22),
               material=mat_log_dark, collection=interior_col, bevel=0.02)
    create_box("Sofa_Backrest", (0.24, 2.05, 0.68), (sofa_x - 0.34, sofa_y, floor_z + 0.62),
               material=mat_fabric_green, collection=interior_col, bevel=0.04)
    create_box("Sofa_Arm_F", (0.92, 0.22, 0.48), (sofa_x, sofa_y - 0.94, floor_z + 0.48),
               material=mat_fabric_green, collection=interior_col, bevel=0.04)
    create_box("Sofa_Arm_B", (0.92, 0.22, 0.48), (sofa_x, sofa_y + 0.94, floor_z + 0.48),
               material=mat_fabric_green, collection=interior_col, bevel=0.04)
    for c_i in range(3):
        cy = sofa_y - 0.56 + c_i * 0.56
        create_box(f"Sofa_Seat_Cushion_{c_i}", (0.68, 0.54, 0.16),
                   (sofa_x + 0.08, cy, floor_z + 0.42), material=mat_fabric_cream, collection=interior_col, bevel=0.035)
        create_box(f"Sofa_Throw_Pillow_{c_i}", (0.18, 0.36, 0.34),
                   (sofa_x - 0.14, cy, floor_z + 0.64),
                   rotation=(0.15, 0.2, 0.1 * (c_i - 1)),
                   material=mat_fabric_red if c_i != 1 else mat_fabric_cream,
                   collection=interior_col, bevel=0.03)

    # Coffee Table between Sofa and Fireplace
    ct_x, ct_y = 1.15, -0.55
    create_box("Coffee_Table_Top", (0.72, 1.35, 0.07), (ct_x, ct_y, floor_z + 0.48),
               material=mat_plank, collection=interior_col, bevel=0.012)
    for lx in [-0.28, 0.28]:
        for ly in [-0.55, 0.55]:
            create_log(f"Coffee_Table_Leg_{lx}_{ly}", 0.42, 0.04,
                       (ct_x + lx, ct_y + ly, floor_z + 0.26), (0, 0, 0), mat_log_dark, interior_col)
    # Teapot & mugs on coffee table
    create_log("Table_Lantern_Base", 0.16, 0.08, (ct_x, ct_y, floor_z + 0.59), (0, 0, 0), mat_brass, interior_col)
    create_log("Table_Lantern_Glass", 0.18, 0.065, (ct_x, ct_y, floor_z + 0.72), (0, 0, 0), mat_lamp, interior_col)
    create_log("Coffee_Mug_1", 0.10, 0.045, (ct_x - 0.12, ct_y - 0.35, floor_z + 0.56), (0, 0, 0), mat_ceramic, interior_col)
    create_log("Coffee_Mug_2", 0.10, 0.045, (ct_x + 0.10, ct_y + 0.32, floor_z + 0.56), (0, 0, 0), mat_ceramic, interior_col)

    # 6. Dining Table & Chairs (Front-Left area near big left window: X = -2.55, Y = -2.55)
    dt_x, dt_y = -2.55, -2.55
    create_box("Dining_Table_Top", (1.10, 1.55, 0.08), (dt_x, dt_y, floor_z + 0.78),
               material=mat_plank, collection=interior_col, bevel=0.015)
    for lx in [-0.44, 0.44]:
        for ly in [-0.64, 0.64]:
            create_log(f"Dining_Leg_{lx}_{ly}", 0.72, 0.05,
                       (dt_x + lx, dt_y + ly, floor_z + 0.42), (0, 0, 0), mat_log_dark, interior_col)

    # 4 Dining Chairs around table
    chair_positions = [
        (dt_x - 0.65, dt_y - 0.38, 0),
        (dt_x - 0.65, dt_y + 0.38, 0),
        (dt_x + 0.65, dt_y - 0.38, math.pi),
        (dt_x + 0.65, dt_y + 0.38, math.pi),
    ]
    for c_idx, (cx, cy, c_rot) in enumerate(chair_positions):
        create_box(f"Chair_Seat_{c_idx}", (0.44, 0.44, 0.05), (cx, cy, floor_z + 0.46),
                   rotation=(0, 0, c_rot), material=mat_plank, collection=interior_col)
        back_dx = -0.19 * math.cos(c_rot)
        create_box(f"Chair_Back_{c_idx}", (0.05, 0.42, 0.48), (cx + back_dx, cy, floor_z + 0.72),
                   rotation=(0, 0, c_rot), material=mat_log_dark, collection=interior_col)
        for clx in [-0.17, 0.17]:
            for cly in [-0.17, 0.17]:
                create_log(f"Chair_Leg_{c_idx}_{clx}_{cly}", 0.42, 0.025,
                           (cx + clx, cy + cly, floor_z + 0.25), (0, 0, 0), mat_log_dark, interior_col)

    # Plates & centerpiece on dining table
    for p_idx, (px, py) in enumerate([(dt_x - 0.28, dt_y - 0.38), (dt_x - 0.28, dt_y + 0.38),
                                      (dt_x + 0.28, dt_y - 0.38), (dt_x + 0.28, dt_y + 0.38)]):
        create_log(f"Dining_Plate_{p_idx}", 0.025, 0.14, (px, py, floor_z + 0.835), (0, 0, 0), mat_ceramic, interior_col)
    create_log("Dining_Candle_Holder", 0.22, 0.05, (dt_x, dt_y, floor_z + 0.92), (0, 0, 0), mat_brass, interior_col)
    create_log("Dining_Candle_Flame", 0.08, 0.03, (dt_x, dt_y, floor_z + 1.06), (0, 0, 0), mat_lamp, interior_col)

    # 7. Kitchenette Counter, Wood Stove & Bookshelf (Back area under the Loft)
    # Kitchen counter along back wall (Y = +cabin_d/2 - 0.55, X from -3.1 to -0.4)
    kc_x, kc_y = -1.95, cabin_d / 2.0 - 0.58
    create_box("Kitchen_Cabinet_Base", (2.4, 0.72, 0.86), (kc_x, kc_y, floor_z + 0.48),
               material=mat_log_dark, collection=interior_col, bevel=0.015)
    create_box("Kitchen_Countertop", (2.52, 0.80, 0.07), (kc_x, kc_y, floor_z + 0.94),
               material=mat_plank, collection=interior_col, bevel=0.01)
    # Cast-iron vintage stove next to counter
    st_x, st_y = -0.25, cabin_d / 2.0 - 0.62
    create_box("CastIron_Stove_Body", (0.78, 0.72, 0.82), (st_x, st_y, floor_z + 0.48),
               material=mat_metal, collection=interior_col, bevel=0.02)
    create_log("Stove_Flue_Pipe", 1.65, 0.08, (st_x, st_y + 0.15, floor_z + 1.68),
               (0, 0, 0), mat_metal, interior_col)
    # Wall shelves with jars on back wall
    for sh_i in range(2):
        sh_z = floor_z + 1.45 + sh_i * 0.45
        create_box(f"Kitchen_Shelf_{sh_i}", (2.1, 0.28, 0.045), (kc_x, kc_y + 0.22, sh_z),
                   material=mat_plank, collection=interior_col)
        for j_i in range(5):
            jx = kc_x - 0.8 + j_i * 0.4
            create_log(f"Spice_Jar_{sh_i}_{j_i}", 0.16, 0.055, (jx, kc_y + 0.20, sh_z + 0.10),
                       (0, 0, 0), mat_ceramic if j_i % 2 == 0 else mat_brass, interior_col)

    # Tall Wooden Bookshelf (Back-Right under loft: X = +2.15, Y = +3.65)
    bs_x, bs_y = 1.95, cabin_d / 2.0 - 0.42
    create_box("Bookshelf_Side_L", (0.06, 0.38, 2.05), (bs_x - 0.75, bs_y, floor_z + 1.08),
               material=mat_log_dark, collection=interior_col)
    create_box("Bookshelf_Side_R", (0.06, 0.38, 2.05), (bs_x + 0.75, bs_y, floor_z + 1.08),
               material=mat_log_dark, collection=interior_col)
    book_mats = [mat_fabric_red, mat_fabric_green, mat_fabric_cream, mat_brass, mat_plank]
    for s_lvl in range(5):
        sz = floor_z + 0.22 + s_lvl * 0.44
        create_box(f"Bookshelf_Shelf_{s_lvl}", (1.52, 0.36, 0.045), (bs_x, bs_y, sz),
                   material=mat_plank, collection=interior_col)
        if s_lvl < 4:
            for b_i in range(11):
                bx = bs_x - 0.62 + b_i * 0.12
                bh = random.uniform(0.24, 0.32)
                create_box(f"Book_{s_lvl}_{b_i}", (0.085, 0.24, bh),
                           (bx, bs_y - 0.02, sz + 0.025 + bh / 2.0),
                           material=book_mats[(s_lvl + b_i) % len(book_mats)],
                           collection=interior_col, bevel=0.005)

    # 8. Upstairs Loft Bedroom (Cozy Bed, Pillows, Blanket, Nightstand & Warm Lamp)
    bed_x, bed_y = 1.35, loft_cy + 0.15
    create_box("Loft_Bed_Frame", (1.95, 2.15, 0.26), (bed_x, bed_y, loft_z + 0.18),
               material=mat_log_dark, collection=interior_col, bevel=0.02)
    create_box("Loft_Bed_Headboard", (1.98, 0.14, 0.95), (bed_x, bed_y + 1.02, loft_z + 0.54),
               material=mat_log_dark, collection=interior_col, bevel=0.02)
    create_box("Loft_Mattress", (1.78, 1.96, 0.24), (bed_x, bed_y - 0.02, loft_z + 0.38),
               material=mat_fabric_cream, collection=interior_col, bevel=0.04)
    create_box("Loft_Duvet_Blanket", (1.82, 1.38, 0.26), (bed_x, bed_y - 0.32, loft_z + 0.40),
               material=mat_fabric_red, collection=interior_col, bevel=0.045)
    for p_side in [-0.45, 0.45]:
        create_box(f"Loft_Pillow_{p_side}", (0.68, 0.42, 0.16),
                   (bed_x + p_side, bed_y + 0.68, loft_z + 0.56),
                   rotation=(0.18, 0, 0), material=mat_fabric_cream, collection=interior_col, bevel=0.035)

    # Nightstand & glowing lamp on the loft
    ns_x, ns_y = bed_x - 1.35, bed_y + 0.72
    create_box("Loft_Nightstand", (0.52, 0.52, 0.54), (ns_x, ns_y, loft_z + 0.32),
               material=mat_log_dark, collection=interior_col, bevel=0.015)
    create_log("Loft_Lamp_Base", 0.22, 0.08, (ns_x, ns_y, loft_z + 0.68), (0, 0, 0), mat_brass, interior_col)
    create_log("Loft_Lamp_Shade", 0.24, 0.16, (ns_x, ns_y, loft_z + 0.88), (0, 0, 0), mat_lamp, interior_col)

    # 9. Hanging Wagon-Wheel Chandelier from the Ridge Beam
    chand_x, chand_y, chand_z = 0.0, -1.15, ridge_z - 1.55
    create_log("Chandelier_Chain", 1.50, 0.025, (chand_x, chand_y, ridge_z - 0.78), (0, 0, 0), mat_metal, interior_col)
    bpy.ops.mesh.primitive_torus_add(
        major_radius=0.68, minor_radius=0.045,
        location=(chand_x, chand_y, chand_z)
    )
    wheel = bpy.context.active_object
    wheel.name = "Chandelier_Wheel"
    wheel.data.materials.append(mat_log_dark)
    link_to_collection(wheel, interior_col)

    # Spokes & 6 warm glowing lantern bulbs on chandelier
    for sp in range(6):
        ang = sp * (math.pi / 3.0)
        lx = chand_x + 0.68 * math.cos(ang)
        ly = chand_y + 0.68 * math.sin(ang)
        create_log(f"Chandelier_Bulb_{sp}", 0.18, 0.065, (lx, ly, chand_z - 0.12),
                   (0, 0, 0), mat_lamp, interior_col)

    # Main Interior Warm Point Lights (Main Room + Loft)
    bpy.ops.object.light_add(type='POINT', location=(chand_x, chand_y, chand_z - 0.25))
    main_int_light = bpy.context.active_object
    main_int_light.name = "Chandelier_Interior_Light"
    main_int_light.data.energy = 420.0
    main_int_light.data.color = (1.0, 0.78, 0.44)
    main_int_light.data.shadow_soft_size = 0.45
    link_to_collection(main_int_light, interior_col)

    bpy.ops.object.light_add(type='POINT', location=(0.2, loft_cy, loft_z + 1.45))
    loft_light = bpy.context.active_object
    loft_light.name = "Loft_Warm_Light"
    loft_light.data.energy = 240.0
    loft_light.data.color = (1.0, 0.76, 0.42)
    loft_light.data.shadow_soft_size = 0.4
    link_to_collection(loft_light, interior_col)

    bpy.ops.object.light_add(type='POINT', location=(-1.5, cabin_d / 2.0 - 1.2, floor_z + 1.95))
    kitchen_light = bpy.context.active_object
    kitchen_light.name = "Kitchen_UnderLoft_Light"
    kitchen_light.data.energy = 190.0
    kitchen_light.data.color = (1.0, 0.80, 0.48)
    kitchen_light.data.shadow_soft_size = 0.35
    link_to_collection(kitchen_light, interior_col)


def build_wooden_cabin():
    clear_scene()

    # Collections
    cabin_col = bpy.data.collections.new("WoodenCabin_Structure")
    bpy.context.scene.collection.children.link(cabin_col)
    interior_col = bpy.data.collections.new("WoodenCabin_Interior")
    bpy.context.scene.collection.children.link(interior_col)
    env_col = bpy.data.collections.new("Environment")
    bpy.context.scene.collection.children.link(env_col)

    # Materials
    mat_log = create_material("Wood_Log", (0.36, 0.20, 0.09), roughness=0.76)
    mat_log_dark = create_material("Wood_Dark", (0.22, 0.12, 0.05), roughness=0.82)
    mat_plank = create_material("Wood_Plank", (0.46, 0.28, 0.14), roughness=0.65)
    mat_floor = create_material("Interior_Hardwood", (0.52, 0.32, 0.16), roughness=0.42)
    mat_shingle = create_material("Roof_Shingle", (0.18, 0.10, 0.05), roughness=0.85)
    mat_stone = create_material("Stone_Base", (0.39, 0.38, 0.36), roughness=0.90)
    mat_stone_dark = create_material("Stone_Dark", (0.28, 0.27, 0.26), roughness=0.92)
    # Semi-transparent clear glass so interior furniture is visible from outside AND glows warmly
    mat_glass = create_material("Window_ClearGlass", (0.95, 0.88, 0.72), roughness=0.08,
                                emission_color=(1.0, 0.76, 0.38), emission_strength=0.45,
                                alpha=0.28, transmission=0.75)
    mat_metal = create_material("Iron_Hardware", (0.12, 0.12, 0.13), roughness=0.35, metallic=0.85)
    mat_brass = create_material("Warm_Brass", (0.78, 0.58, 0.22), roughness=0.28, metallic=0.88)
    mat_ceramic = create_material("Cream_Ceramic", (0.92, 0.89, 0.82), roughness=0.25)
    mat_fabric_red = create_material("Fabric_RustRed", (0.62, 0.16, 0.14), roughness=0.88)
    mat_fabric_cream = create_material("Fabric_WarmCream", (0.88, 0.82, 0.70), roughness=0.85)
    mat_fabric_green = create_material("Fabric_ForestGreen", (0.16, 0.32, 0.20), roughness=0.86)
    mat_ember = create_material("Fire_Ember", (1.0, 0.38, 0.05), roughness=0.4,
                                emission_color=(1.0, 0.42, 0.06), emission_strength=14.0)
    mat_lamp = create_material("Warm_Lamp_Bulb", (1.0, 0.85, 0.55), roughness=0.2,
                               emission_color=(1.0, 0.78, 0.38), emission_strength=9.0)
    mat_ground = create_material("Forest_Ground", (0.14, 0.22, 0.10), roughness=0.95)
    mat_foliage = create_material("Pine_Foliage", (0.08, 0.24, 0.09), roughness=0.85)

    materials = {
        "log": mat_log, "log_dark": mat_log_dark, "plank": mat_plank, "floor": mat_floor,
        "stone": mat_stone, "stone_dark": mat_stone_dark, "metal": mat_metal, "brass": mat_brass,
        "ceramic": mat_ceramic, "fabric_red": mat_fabric_red, "fabric_cream": mat_fabric_cream,
        "fabric_green": mat_fabric_green, "ember": mat_ember, "lamp": mat_lamp,
    }

    # Enlarged Cabin Dimensions (Spacious 2-level family log cabin)
    cabin_w = 7.4    # X width (was 4.4)
    cabin_d = 8.8    # Y depth (was 5.2)
    porch_d = 2.5    # Front porch depth (was 1.8)
    base_h = 0.52    # Stone foundation height
    log_r = 0.15     # Log radius
    log_step = 0.25  # Vertical spacing per log layer
    num_layers = 15  # Taller walls to fit ground floor + loft (3.75m wall height)
    floor_z = base_h + 0.06
    wall_top_z = base_h + num_layers * log_step

    # 1. Stone Foundation & Porch Deck
    total_d = cabin_d + porch_d
    center_y = -porch_d / 2.0
    create_box("Foundation_Base", (cabin_w + 0.45, total_d + 0.45, base_h),
               (0, center_y, base_h / 2.0), material=mat_stone, collection=cabin_col, bevel=0.03)

    # Decorative perimeter stones
    for side_x in [-1, 1]:
        for i in range(22):
            sy = -cabin_d / 2.0 - porch_d + 0.3 + i * (total_d / 22.0)
            create_box(f"Foundation_Stone_X_{side_x}_{i}",
                       (0.20, 0.45, base_h * 0.92),
                       (side_x * (cabin_w / 2.0 + 0.20), sy, base_h * 0.46),
                       material=mat_stone_dark if i % 2 == 0 else mat_stone,
                       collection=cabin_col, bevel=0.025)

    # Front Porch Wooden Deck Planks
    porch_front_y = -cabin_d / 2.0 - porch_d
    porch_cy = -cabin_d / 2.0 - porch_d / 2.0
    num_porch_planks = 38
    p_plank_w = (cabin_w + 0.25) / num_porch_planks
    for i in range(num_porch_planks):
        px = -(cabin_w + 0.25) / 2.0 + (i + 0.5) * p_plank_w
        create_box(f"Porch_Deck_Plank_{i}", (p_plank_w * 0.92, porch_d + 0.22, 0.06),
                   (px, porch_cy, base_h + 0.03),
                   material=mat_plank, collection=cabin_col, bevel=0.006)

    # Wide Front Steps
    for s in range(4):
        step_h = base_h * (4 - s) / 4.5
        step_y = porch_front_y - 0.22 - s * 0.30
        create_box(f"Front_Step_{s}", (2.1, 0.30, 0.075),
                   (0, step_y, step_h), material=mat_plank, collection=cabin_col, bevel=0.01)
    for sx in [-0.98, 0.98]:
        create_box(f"Step_Support_{sx}", (0.10, 1.25, base_h * 0.82),
                   (sx, porch_front_y - 0.65, base_h * 0.42),
                   material=mat_log_dark, collection=cabin_col, bevel=0.01)

    # 2. Interlocking Log Walls with Real Door & Window Cutouts
    overhang = 0.45
    door_w = 1.35
    door_layers = 9  # 2.25m tall front door opening

    # Window openings definition:
    # Front wall: Left window (-2.75 to -1.35) & Right window (+1.35 to +2.75) on layers 3..8
    # Left wall: Front dining window (-3.1 to -1.5) & Back kitchen window (+1.0 to +2.6) on layers 3..8
    # Right wall: Window beside fireplace (-3.1 to -1.6) on layers 3..8
    # Back wall: Lower window (-2.5 to -0.9) on layers 4..8, and Loft window (+0.6 to +2.2) on layers 11..14
    x_span = (-cabin_w / 2.0 - overhang, cabin_w / 2.0 + overhang)
    y_span = (-cabin_d / 2.0 - overhang, cabin_d / 2.0 + overhang)

    for layer in range(num_layers):
        z_x = floor_z + layer * log_step + log_r * 0.8
        z_y = z_x + log_step * 0.5

        # Front Wall (y = -cabin_d / 2.0)
        f_openings = []
        if layer < door_layers:
            f_openings.append((-door_w / 2.0, door_w / 2.0))
        if 3 <= layer <= 8:
            f_openings.append((-2.85, -1.35))
            f_openings.append((1.35, 2.85))
        build_wall_segments(f"Wall_Front_L{layer}", x_span, f_openings,
                            -cabin_d / 2.0, z_x, 'X', log_r, mat_log, cabin_col)

        # Back Wall (y = +cabin_d / 2.0)
        b_openings = []
        if 11 <= layer <= 14:
            b_openings.append((0.55, 2.15))
        build_wall_segments(f"Wall_Back_L{layer}", x_span, b_openings,
                            cabin_d / 2.0, z_x, 'X', log_r, mat_log, cabin_col)

        # Left Wall (x = -cabin_w / 2.0)
        l_openings = []
        if 3 <= layer <= 8:
            l_openings.append((-3.15, -1.45))
            l_openings.append((0.95, 2.55))
        if 11 <= layer <= 14:
            l_openings.append((1.25, 2.65))  # Upper loft side window
        build_wall_segments(f"Wall_Left_L{layer}", y_span, l_openings,
                            -cabin_w / 2.0, z_y, 'Y', log_r, mat_log, cabin_col)

        # Right Wall (x = +cabin_w / 2.0)
        r_openings = []
        if 3 <= layer <= 8:
            r_openings.append((-3.15, -1.55))
        build_wall_segments(f"Wall_Right_L{layer}", y_span, r_openings,
                            cabin_w / 2.0, z_y, 'Y', log_r, mat_log, cabin_col)

    # 3. Gable Triangles (with Front Upper Loft Window) & Roof Purlins
    roof_pitch = math.radians(35)
    gable_layers = 10
    for g in range(gable_layers):
        gz = wall_top_z + (g + 0.5) * log_step
        half_span = (cabin_w / 2.0) - (g + 0.5) * (log_step / math.tan(roof_pitch))
        if half_span > 0.25:
            g_span = (-half_span - 0.12, half_span + 0.12)
            # Front Gable has an upper loft window on gable layers 1..5
            fg_ops = [(-0.85, 0.85)] if 1 <= g <= 5 else []
            build_wall_segments(f"Gable_Front_{g}", g_span, fg_ops,
                                -cabin_d / 2.0, gz, 'X', log_r * 0.92, mat_log, cabin_col)
            build_wall_segments(f"Gable_Back_{g}", g_span, fg_ops,
                                cabin_d / 2.0, gz, 'X', log_r * 0.92, mat_log, cabin_col)

            # Roof purlins running full length
            purlin_len = total_d + 1.1
            for side_s in [-1, 1]:
                create_log(f"Purlin_{g}_{side_s}", purlin_len, log_r * 0.72,
                           (side_s * half_span, center_y, gz + 0.06),
                           (math.pi / 2, 0, 0), mat_log_dark, cabin_col)

    # Ridge Beam
    ridge_z = wall_top_z + gable_layers * log_step + 0.06
    create_log("Ridge_Beam", total_d + 1.3, log_r * 1.1,
               (0, center_y, ridge_z), (math.pi / 2, 0, 0), mat_log_dark, cabin_col)

    # 4. Roof Decks & Staggered Wooden Shingles
    slope_len = (cabin_w / 2.0 + 0.85) / math.cos(roof_pitch)
    roof_len_y = total_d + 1.15
    mid_span_x = (cabin_w / 2.0 + 0.85) / 2.0
    mid_span_z = ridge_z - (mid_span_x * math.tan(roof_pitch))

    for side_s, name_s in [(-1, "Left"), (1, "Right")]:
        tilt = roof_pitch * side_s
        create_box(f"Roof_Base_{name_s}", (slope_len, roof_len_y, 0.09),
                   (side_s * mid_span_x, center_y, mid_span_z + 0.06),
                   rotation=(0, tilt, 0), material=mat_plank, collection=cabin_col, bevel=0.01)

        num_rows = 13
        shingle_cols = 24
        for r in range(num_rows):
            frac = (r + 0.5) / num_rows
            dist_from_ridge = slope_len * (1.0 - frac)
            rx = side_s * (dist_from_ridge * math.cos(roof_pitch))
            rz = ridge_z - (dist_from_ridge * math.sin(roof_pitch)) + 0.13
            for c in range(shingle_cols):
                sy = center_y - roof_len_y / 2.0 + (c + 0.5) * (roof_len_y / shingle_cols)
                jitter_z = random.uniform(-0.008, 0.008)
                jitter_rot = random.uniform(-0.018, 0.018)
                create_box(f"Shingle_{name_s}_{r}_{c}",
                           (slope_len / num_rows * 1.18, (roof_len_y / shingle_cols) * 0.93, 0.035),
                           (rx, sy, rz + jitter_z),
                           rotation=(jitter_rot, tilt + random.uniform(-0.012, 0.012), 0),
                           material=mat_shingle, collection=cabin_col, bevel=0.005)

    # Fascia boards
    for y_name, fy in [("Front", center_y - roof_len_y / 2.0 + 0.05), ("Back", center_y + roof_len_y / 2.0 - 0.05)]:
        for side_s in [-1, 1]:
            tilt = roof_pitch * side_s
            create_box(f"Fascia_{y_name}_{side_s}", (slope_len + 0.10, 0.07, 0.18),
                       (side_s * mid_span_x, fy, mid_span_z + 0.08),
                       rotation=(0, tilt, 0), material=mat_log_dark, collection=cabin_col, bevel=0.008)

    # 5. Front Porch Columns, Beams & Railings
    porch_top_z = wall_top_z - 0.05
    post_h = porch_top_z - floor_z
    post_z = floor_z + post_h / 2.0
    post_xs = [-cabin_w / 2.0, -1.15, 1.15, cabin_w / 2.0]
    for idx, px in enumerate(post_xs):
        create_log(f"Porch_Post_{idx}", post_h, log_r * 0.88,
                   (px, porch_front_y + 0.14, post_z), (0, 0, 0), mat_log, cabin_col)

    create_log("Porch_Header_Beam", cabin_w + 0.8, log_r * 0.95,
               (0, porch_front_y + 0.14, porch_top_z), (0, math.pi / 2, 0), mat_log_dark, cabin_col)

    # Front porch railings
    rail_spans = [
        (-cabin_w / 2.0, -1.15, porch_front_y + 0.14, "Front_Left"),
        (1.15, cabin_w / 2.0, porch_front_y + 0.14, "Front_Right"),
    ]
    for x1, x2, ry, rname in rail_spans:
        rlen = abs(x2 - x1)
        rcx = (x1 + x2) / 2.0
        create_log(f"Rail_Top_{rname}", rlen, 0.055, (rcx, ry, base_h + 0.92), (0, math.pi / 2, 0), mat_plank, cabin_col)
        create_log(f"Rail_Bot_{rname}", rlen, 0.045, (rcx, ry, base_h + 0.25), (0, math.pi / 2, 0), mat_plank, cabin_col)
        num_bal = 9
        for b in range(num_bal):
            bx = x1 + (b + 1) * (rlen / (num_bal + 1))
            create_log(f"Baluster_{rname}_{b}", 0.65, 0.03, (bx, ry, base_h + 0.58), (0, 0, 0), mat_plank, cabin_col)

    # Side porch railings
    for side_s, sname in [(-1, "Left"), (1, "Right")]:
        sx = side_s * (cabin_w / 2.0)
        sy_mid = -cabin_d / 2.0 - porch_d / 2.0 + 0.07
        rlen = porch_d - 0.16
        create_log(f"Side_Rail_Top_{sname}", rlen, 0.055, (sx, sy_mid, base_h + 0.92), (math.pi / 2, 0, 0), mat_plank, cabin_col)
        create_log(f"Side_Rail_Bot_{sname}", rlen, 0.045, (sx, sy_mid, base_h + 0.25), (math.pi / 2, 0, 0), mat_plank, cabin_col)
        for b in range(7):
            by = porch_front_y + 0.28 + b * (rlen / 7.5)
            create_log(f"Side_Baluster_{sname}_{b}", 0.65, 0.03, (sx, by, base_h + 0.58), (0, 0, 0), mat_plank, cabin_col)

    # Porch Rocking Chair / Bench on Front Right Porch
    bench_x, bench_y = 2.45, -cabin_d / 2.0 - 0.65
    create_box("Porch_Bench_Seat", (1.35, 0.52, 0.06), (bench_x, bench_y, floor_z + 0.44),
               material=mat_plank, collection=cabin_col)
    create_box("Porch_Bench_Back", (1.35, 0.06, 0.52), (bench_x, bench_y + 0.24, floor_z + 0.72),
               rotation=(0.15, 0, 0), material=mat_plank, collection=cabin_col)
    for blx in [-0.55, 0.55]:
        create_box(f"Porch_Bench_Leg_{blx}", (0.08, 0.48, 0.44), (bench_x + blx, bench_y, floor_z + 0.22),
                   material=mat_log_dark, collection=cabin_col)

    # 6. Front Door (Swung Open at 42 degrees so you can see inside!)
    door_h = door_layers * log_step
    door_z = floor_z + door_h / 2.0
    fy = -cabin_d / 2.0
    create_box("Door_Frame_L", (0.13, 0.38, door_h + 0.12), (-door_w / 2.0, fy, door_z), material=mat_log_dark, collection=cabin_col)
    create_box("Door_Frame_R", (0.13, 0.38, door_h + 0.12), (door_w / 2.0, fy, door_z), material=mat_log_dark, collection=cabin_col)
    create_box("Door_Frame_Top", (door_w + 0.28, 0.40, 0.14), (0, fy, floor_z + door_h + 0.06), material=mat_log_dark, collection=cabin_col)

    # Hinged open door leaf (pivoted at left jamb x = -door_w/2, swung inward +Y)
    open_angle = math.radians(48)
    hinge_x = -door_w / 2.0 + 0.06
    hinge_y = fy + 0.05
    leaf_w = door_w - 0.12
    leaf_cx = hinge_x + (leaf_w / 2.0) * math.cos(open_angle)
    leaf_cy = hinge_y + (leaf_w / 2.0) * math.sin(open_angle)
    create_box("Door_Leaf_Open", (leaf_w, 0.09, door_h - 0.06),
               (leaf_cx, leaf_cy, door_z), rotation=(0, 0, open_angle),
               material=mat_plank, collection=cabin_col, bevel=0.01)
    create_box("Door_CrossBrace_Top", (leaf_w * 0.88, 0.12, 0.10),
               (leaf_cx, leaf_cy, door_z + 0.62), rotation=(0, 0, open_angle),
               material=mat_log_dark, collection=cabin_col)
    create_box("Door_CrossBrace_Bot", (leaf_w * 0.88, 0.12, 0.10),
               (leaf_cx, leaf_cy, door_z - 0.62), rotation=(0, 0, open_angle),
               material=mat_log_dark, collection=cabin_col)

    # 7. All Transparent Windows (Framed into the Cutouts)
    win_mid_z = floor_z + 6.0 * log_step
    win_h = 5.6 * log_step
    # Front Left & Right Windows
    build_window_unit("Win_Front_Left", (-2.10, fy, win_mid_z), 'X', 1.50, win_h,
                      mat_log_dark, mat_plank, mat_glass, cabin_col, shutters=True)
    build_window_unit("Win_Front_Right", (2.10, fy, win_mid_z), 'X', 1.50, win_h,
                      mat_log_dark, mat_plank, mat_glass, cabin_col, shutters=True)
    # Front Gable Loft Window
    gable_win_z = wall_top_z + 3.5 * log_step
    build_window_unit("Win_Gable_Front", (0.0, fy, gable_win_z), 'X', 1.70, 5.0 * log_step,
                      mat_log_dark, mat_plank, mat_glass, cabin_col, shutters=False)
    build_window_unit("Win_Gable_Back", (0.0, cabin_d / 2.0, gable_win_z), 'X', 1.70, 5.0 * log_step,
                      mat_log_dark, mat_plank, mat_glass, cabin_col, shutters=False)

    # Left Wall Windows (Dining + Kitchen + Loft)
    lx = -cabin_w / 2.0
    build_window_unit("Win_Left_Dining", (lx, -2.30, win_mid_z), 'Y', 1.70, win_h,
                      mat_log_dark, mat_plank, mat_glass, cabin_col, shutters=True)
    build_window_unit("Win_Left_Kitchen", (lx, 1.75, win_mid_z), 'Y', 1.60, win_h,
                      mat_log_dark, mat_plank, mat_glass, cabin_col, shutters=True)
    build_window_unit("Win_Left_Loft", (lx, 1.95, floor_z + 13.0 * log_step), 'Y', 1.40, 3.8 * log_step,
                      mat_log_dark, mat_plank, mat_glass, cabin_col, shutters=False)

    # Right Wall Window
    rx = cabin_w / 2.0
    build_window_unit("Win_Right_Living", (rx, -2.35, win_mid_z), 'Y', 1.60, win_h,
                      mat_log_dark, mat_plank, mat_glass, cabin_col, shutters=True)

    # 8. Populate Rich Interior Details
    build_interior(cabin_w, cabin_d, floor_z, wall_top_z, ridge_z, interior_col, materials)

    # 9. Exterior Stone Chimney on Right Side (+X, aligned with interior fireplace at Y = -0.35)
    chim_x = cabin_w / 2.0 + 0.38
    chim_y = -0.35
    create_box("Chimney_Base", (1.05, 1.95, 3.2), (chim_x, chim_y, 1.6), material=mat_stone, collection=cabin_col, bevel=0.04)
    create_box("Chimney_Mid", (0.86, 1.45, 2.4), (chim_x - 0.06, chim_y, 4.1), material=mat_stone_dark, collection=cabin_col, bevel=0.04)
    create_box("Chimney_Stack", (0.72, 1.08, 2.6), (chim_x - 0.12, chim_y, 6.2), material=mat_stone, collection=cabin_col, bevel=0.03)
    create_box("Chimney_Cap", (0.88, 1.24, 0.16), (chim_x - 0.12, chim_y, 7.55), material=mat_stone_dark, collection=cabin_col, bevel=0.02)
    for s_idx in range(18):
        sz = 0.4 + s_idx * 0.39
        w_factor = 1.0 if sz < 3.1 else (0.82 if sz < 5.2 else 0.68)
        create_box(f"Chimney_Stone_{s_idx}",
                   (1.08 * w_factor, 0.52 * w_factor, 0.30),
                   (chim_x + (0.04 if s_idx % 2 == 0 else -0.04),
                    chim_y + (0.26 if s_idx % 2 == 0 else -0.26) * w_factor,
                    sz),
                   material=mat_stone_dark if s_idx % 2 == 0 else mat_stone,
                   collection=cabin_col, bevel=0.03)

    # 10. Exterior Firewood Stack & Surrounding Forest Environment
    for row in range(5):
        for col_i in range(7 - row):
            ly = -0.4 + col_i * 0.21 + row * 0.10
            lz = floor_z + 0.06 + row * 0.16
            create_log(f"Firewood_{row}_{col_i}", 0.65, 0.09,
                       (-cabin_w / 2.0 - 0.42, ly, lz), (0, math.pi / 2, 0),
                       mat_log_dark if (row + col_i) % 2 == 0 else mat_log, cabin_col)

    # Larger Ground Island
    bpy.ops.mesh.primitive_cylinder_add(vertices=64, radius=22.0, depth=0.25, location=(0, 0, -0.12))
    ground = bpy.context.active_object
    ground.name = "Ground_Island"
    ground.data.materials.append(mat_ground)
    add_bevel(ground, width=0.05, segments=2)
    link_to_collection(ground, env_col)

    # Framed Pine Trees around the larger cabin
    tree_coords = [(-8.2, 4.5, 1.35), (7.6, -3.5, 1.20), (-9.2, -2.5, 1.10), (7.2, 5.2, 1.45), (-5.5, 7.8, 1.25)]
    for t_i, (tx, ty, tscale) in enumerate(tree_coords):
        create_log(f"Pine_Trunk_{t_i}", 2.0 * tscale, 0.24 * tscale,
                   (tx, ty, 1.0 * tscale), (0, 0, 0), mat_log_dark, env_col)
        for tier in range(4):
            cone_r = (1.75 - tier * 0.34) * tscale
            cone_h = (1.6 - tier * 0.16) * tscale
            cone_z = (1.75 + tier * 0.92) * tscale
            bpy.ops.mesh.primitive_cone_add(vertices=16, radius1=cone_r, radius2=0.05,
                                            depth=cone_h, location=(tx, ty, cone_z))
            cone = bpy.context.active_object
            cone.name = f"Pine_Foliage_{t_i}_{tier}"
            cone.data.materials.append(mat_foliage)
            link_to_collection(cone, env_col)

    # 11. Exterior Lighting & Dual Cameras (Exterior + Interior)
    bpy.ops.object.light_add(type='SUN', location=(12, -14, 16),
                             rotation=(math.radians(50), math.radians(16), math.radians(34)))
    sun = bpy.context.active_object
    sun.name = "Sun_KeyLight"
    sun.data.energy = 3.8
    sun.data.color = (1.0, 0.91, 0.78)
    sun.data.angle = math.radians(4.5)
    link_to_collection(sun, env_col)

    # Warm Porch Lanterns (Left & Right of front door)
    for lx_pos in [-0.95, 0.95]:
        bpy.ops.object.light_add(type='POINT', location=(lx_pos, -cabin_d / 2.0 - 0.45, wall_top_z - 0.55))
        lantern = bpy.context.active_object
        lantern.name = f"Porch_Lantern_{lx_pos}"
        lantern.data.energy = 160.0
        lantern.data.color = (1.0, 0.70, 0.32)
        lantern.data.shadow_soft_size = 0.28
        link_to_collection(lantern, env_col)

    # Sky Fill Area Light
    bpy.ops.object.light_add(type='AREA', location=(-12, -12, 11),
                             rotation=(math.radians(54), 0, math.radians(-38)))
    fill = bpy.context.active_object
    fill.name = "Sky_FillLight"
    fill.data.energy = 500.0
    fill.data.size = 10.0
    fill.data.color = (0.70, 0.84, 1.0)
    link_to_collection(fill, env_col)

    # World background
    world = bpy.context.scene.world
    if not world:
        world = bpy.data.worlds.new("World")
        bpy.context.scene.world = world
    world.use_nodes = True
    bg = world.node_tree.nodes.get("Background")
    if bg:
        bg.inputs["Color"].default_value = (0.12, 0.16, 0.24, 1.0)
        bg.inputs["Strength"].default_value = 0.85

    # Camera 1: Exterior 3/4 View
    bpy.ops.object.camera_add(
        location=(-13.2, -16.5, 7.6),
        rotation=(math.radians(69.0), 0.0, math.radians(-38.0))
    )
    cam_ext = bpy.context.active_object
    cam_ext.name = "Cabin_Exterior_Camera"
    cam_ext.data.lens = 34

    # Camera 2: Interior Wide-Angle View (from front-left doorway looking across living room, fireplace, stairs & loft)
    bpy.ops.object.camera_add(
        location=(-2.35, -3.65, floor_z + 1.95),
        rotation=(math.radians(82.0), 0.0, math.radians(-32.0))
    )
    cam_int = bpy.context.active_object
    cam_int.name = "Cabin_Interior_Camera"
    cam_int.data.lens = 21

    bpy.context.scene.camera = cam_ext
    return cam_ext, cam_int


if __name__ == "__main__":
    cam_ext, cam_int = build_wooden_cabin()

    out_dir = os.path.dirname(os.path.abspath(__file__))
    blend_path = os.path.join(out_dir, "wooden_cabin.blend")
    glb_path = os.path.join(out_dir, "wooden_cabin.glb")
    preview_ext_path = os.path.join(out_dir, "cabin_preview.png")
    preview_int_path = os.path.join(out_dir, "cabin_interior_preview.png")

    # Save .blend file
    bpy.ops.wm.save_as_mainfile(filepath=blend_path)
    print(f"Saved Blender file: {blend_path}")

    # Export GLB
    try:
        bpy.ops.export_scene.gltf(filepath=glb_path, export_format='GLB')
        print(f"Exported GLB file: {glb_path}")
    except Exception as e:
        print(f"GLB export note: {e}")

    # Render Exterior & Interior Previews using Cycles CPU
    scene = bpy.context.scene
    scene.render.resolution_x = 960
    scene.render.resolution_y = 540
    scene.render.engine = 'CYCLES'
    scene.cycles.device = 'CPU'
    scene.cycles.samples = 24
    scene.cycles.use_denoising = False

    # 1. Exterior render
    scene.camera = cam_ext
    scene.render.filepath = preview_ext_path
    bpy.ops.render.render(write_still=True)
    print(f"Rendered exterior preview: {preview_ext_path}")

    # 2. Interior render
    scene.camera = cam_int
    scene.render.filepath = preview_int_path
    bpy.ops.render.render(write_still=True)
    print(f"Rendered interior preview: {preview_int_path}")
