#!/usr/bin/env python3
"""Pacote de execução da Oficina do Sítio — pranchas PR-03 a PR-09 (PNG) +
`execucao-oficina.pdf` (A3 paisagem): capa + PR-01..PR-09 + memorial + lista.

Base: `projetos/canteiro-obras.md` §2.4 (locação) e §12 (oficina).
Medidas de projeto preliminar — confirmar no estrutural/elétrico
(pendências 9/10/11).
"""

import csv

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.patches as patches

BASE = "/home/paulo/Documentos/Paulo/Sítio"
DES = f"{BASE}/referencias-drive/desenhos"
A3 = (16.5, 11.7)  # polegadas, paisagem

PILARES = [
    (0, 0),
    (1.5, 0),
    (4.5, 0),
    (6, 0),
    (0, 3),
    (6, 3),
    (0, 6),
    (6, 6),
    (0, 9),
    (6, 9),
    (0, 12),
    (1.5, 12),
    (4.5, 12),
    (6, 12),
]


def nova_prancha(titulo, subtitulo=""):
    fig, ax = plt.subplots(figsize=A3)
    ax.set_aspect("equal")
    ax.axis("off")
    ax.set_facecolor("#ffffff")
    fig.suptitle(titulo, fontsize=16, fontweight="bold", y=0.96)
    if subtitulo:
        ax.set_title(subtitulo, fontsize=10, color="#555", pad=8)
    return fig, ax


def cotas_retangulo(ax, x0, y0, w, h):
    """Cotas externas de um retângulo."""
    ax.annotate(
        "",
        xy=(x0, y0 - 0.5),
        xytext=(x0 + w, y0 - 0.5),
        arrowprops=dict(arrowstyle="<->", color="#666", lw=1),
    )
    ax.text(
        x0 + w / 2,
        y0 - 0.8,
        f"{w:.2f} m".replace(".", ","),
        fontsize=9,
        ha="center",
        color="#666",
    )
    ax.annotate(
        "",
        xy=(x0 - 0.5, y0),
        xytext=(x0 - 0.5, y0 + h),
        arrowprops=dict(arrowstyle="<->", color="#666", lw=1),
    )
    ax.text(
        x0 - 0.9,
        y0 + h / 2,
        f"{h:.2f} m".replace(".", ","),
        fontsize=9,
        ha="center",
        va="center",
        color="#666",
        rotation=90,
    )


# ================= PR-03 FUNDAÇÃO =================
PILARES_OFICINA = [
    (0, 0),
    (1.5, 0),
    (4.5, 0),
    (6, 0),
    (0, 3),
    (6, 3),
    (0, 6),
    (6, 6),
    (0, 9),
    (6, 9),
    (0, 12),
    (1.5, 12),
    (4.5, 12),
    (6, 12),
]
PILARES_ANEXO = [(0, -4), (3, -4), (6, -4)]
fig, ax = nova_prancha(
    "PR-03 — Fundação: radier contínuo + sapatas + dreno",
    "concreto 10 cm · 6×16 m = 96 m² · tela soldada · sapatas 50×50×30 nos 17 pilares",
)
ax.set_xlim(-4, 26)
ax.set_ylim(-7, 15)
# radier contínuo (oficina 6x12 + anexo 6x4, uma concretagem)
ax.add_patch(
    patches.Rectangle(
        (0, -4), 6, 16, linewidth=2, edgecolor="black", facecolor="#e0e0e0"
    )
)
ax.text(
    3,
    6,
    "RADIER 10 cm\n96 m² · 9,6 m³\ntela soldada\n(bitola A CONFIRMAR)",
    fontsize=10,
    ha="center",
    va="center",
    fontweight="bold",
)
# sapatas (14 da oficina + 3 da fachada sul do anexo)
for px, py in PILARES_OFICINA + PILARES_ANEXO:
    ax.add_patch(
        patches.Rectangle(
            (px - 0.25, py - 0.25),
            0.5,
            0.5,
            linewidth=1.2,
            edgecolor="black",
            facecolor="#9e9e9e",
            hatch="///",
        )
    )
ax.text(3, 12.7, "17 sapatas 50×50×30 + esperas", fontsize=8, ha="center", color="#333")
# anexo tracejado
ax.add_patch(
    patches.Rectangle(
        (0, -4),
        6,
        4,
        linewidth=1.5,
        edgecolor="#4e342e",
        facecolor="none",
        linestyle=(0, (4, 2)),
    )
)
ax.text(3, -3.4, "anexo betoneira", fontsize=8, ha="center", color="#4e342e")
# dreno
ax.add_patch(
    patches.Rectangle(
        (-0.6, -4.6),
        7.2,
        17.2,
        linewidth=1.2,
        edgecolor="#0288d1",
        facecolor="none",
        linestyle="--",
    )
)
ax.text(6.9, 6, "dreno\nperimetral", fontsize=8, ha="left", color="#0288d1")
cotas_retangulo(ax, 0, -4, 6, 16)
# corte AA
ax.text(13, 12.5, "CORTE AA (sem escala)", fontsize=10, fontweight="bold", ha="center")
ax.plot([9, 17], [9, 9], color="#8B4513", linewidth=3)  # solo
ax.text(9.2, 8.6, "solo natural", fontsize=8, color="#8B4513")
ax.add_patch(
    patches.Rectangle(
        (10, 9.0), 6, 0.25, linewidth=1, edgecolor="black", facecolor="#bcaaa4"
    )
)
ax.text(13, 9.12, "brita 5 cm", fontsize=7, ha="center")
ax.add_patch(
    patches.Rectangle(
        (10, 9.25), 6, 0.5, linewidth=1.5, edgecolor="black", facecolor="#cfd8dc"
    )
)
ax.text(13, 9.5, "radier 10 cm", fontsize=8, ha="center", fontweight="bold")
ax.add_patch(
    patches.Rectangle(
        (12.4, 8.4),
        1.2,
        0.6,
        linewidth=1.2,
        edgecolor="black",
        facecolor="#9e9e9e",
        hatch="///",
    )
)
ax.text(13, 8.1, "sapata 50×50×30", fontsize=7, ha="center")
ax.plot([12.85, 12.85], [9.0, 11.2], "--", color="black", linewidth=1.5)
ax.plot([13.15, 13.15], [9.0, 11.2], "--", color="black", linewidth=1.5)
ax.add_patch(
    patches.Rectangle(
        (12.85, 9.75), 0.3, 1.45, linewidth=1.5, edgecolor="black", facecolor="none"
    )
)
ax.text(14.2, 10.4, "pilar 15×15\n+ esperas", fontsize=7, ha="left")
fig.savefig(f"{DES}/oficina-PR-03-fundacao.png", dpi=150, bbox_inches="tight")
plt.close(fig)
print("PR-03 OK")

# ================= PR-04 COBERTURA =================
fig, ax = nova_prancha(
    "PR-04 — Cobertura: cumeeira N-S, telha cerâmica",
    "vão ~3 m por água · pé-direito 3,0 m · cumeeira ~3,9 m (30%) · beiral 0,5 m",
)
ax.set_xlim(-4, 26)
ax.set_ylim(-5.5, 15)
# planta: beiral + edificação + cumeeira + terças + calhas
ax.add_patch(
    patches.Rectangle(
        (-0.5, -0.5),
        7,
        13,
        linewidth=1,
        edgecolor="#999",
        facecolor="none",
        linestyle="--",
    )
)
ax.text(6.9, 12.8, "beiral 0,5 m", fontsize=8, color="#999")
ax.add_patch(
    patches.Rectangle(
        (0, 0), 6, 12, linewidth=2, edgecolor="black", facecolor="#fff8e1"
    )
)
ax.plot([3, 3], [0, 12], color="#cc0000", linewidth=2.5, linestyle=(0, (4, 2)))
ax.text(
    3, 12.4, "cumeeira N-S", fontsize=8, ha="center", color="#cc0000", fontweight="bold"
)
for xt in (1.5, 4.5):
    ax.plot([xt, xt], [0, 12], color="#8B4513", linewidth=1.2)
ax.text(1.5, -0.9, "terças", fontsize=8, ha="center", color="#8B4513")
ax.plot([0, 0], [0, 12], color="#0288d1", linewidth=4)
ax.plot([6, 6], [0, 12], color="#0288d1", linewidth=4)
ax.text(-0.5, 6, "calha", fontsize=8, ha="right", color="#0288d1", rotation=90)
ax.text(6.5, 6, "calha", fontsize=8, ha="left", color="#0288d1", rotation=90)
# anexo da betoneira ao sul: uma água caindo p/ sul, apoiada na parede sul
ax.add_patch(
    patches.Rectangle(
        (0, -4),
        6,
        4,
        linewidth=1.5,
        edgecolor="black",
        facecolor="#fff8e1",
        alpha=0.6,
    )
)
ax.plot([0, 6], [-0.2, -3.8], color="#8B4513", linewidth=2.5)
ax.plot([0, 6], [0.3, -3.3], color="#8B4513", linewidth=1.2, linestyle=(0, (3, 2)))
ax.text(
    3,
    -2.0,
    "ANEXO 6×4\numa água p/ sul (30%)",
    fontsize=8,
    ha="center",
    va="center",
    fontweight="bold",
    color="#4e342e",
)
for px in (0, 3, 6):
    ax.add_patch(
        patches.Rectangle(
            (px - 0.15, -4.15),
            0.3,
            0.3,
            linewidth=1.2,
            edgecolor="black",
            facecolor="#616161",
            zorder=6,
        )
    )
ax.text(
    3, -4.6, "3 pilares 15×15 na fachada sul", fontsize=7, ha="center", color="#333"
)
cotas_retangulo(ax, 0, 0, 6, 12)
# corte transversal
ax.text(
    15.5,
    12.5,
    "CORTE TRANSVERSAL (sem escala)",
    fontsize=10,
    fontweight="bold",
    ha="center",
)
# perfil: beiral esq (9.5,3.0) -> cumeeira (12.5,3.9) -> beiral dir (15.5,3.0)
ax.plot([9.5, 12.5, 15.5], [3.0, 3.9, 3.0], color="black", linewidth=2.5)
ax.plot([10, 10], [0, 3.0], color="black", linewidth=2)  # pilares
ax.plot([15, 15], [0, 3.0], color="black", linewidth=2)
ax.plot([9.5, 15.5], [0, 0], color="#8B4513", linewidth=3)
ax.text(12.5, 0.5, "radier", fontsize=8, ha="center", color="#8B4513")
ax.text(10, 1.5, "pé-direito\n3,0 m", fontsize=7, ha="right")
ax.text(12.5, 4.3, "cumeeira ~3,9 m", fontsize=8, ha="center", color="#cc0000")
ax.text(11.2, 3.75, "30%", fontsize=8, ha="center", color="#555")
ax.text(9.7, 2.5, "beiral 0,5", fontsize=7, ha="center", color="#999")
ax.text(15.3, 2.5, "beiral 0,5", fontsize=7, ha="center", color="#999")
ax.text(
    12.5,
    6.5,
    "telha cerâmica s/ madeira de lei\n"
    "(terças + caibros + ripas — bitolas A CONFIRMAR)",
    fontsize=8,
    ha="center",
    color="#555",
)
fig.savefig(f"{DES}/oficina-PR-04-cobertura.png", dpi=150, bbox_inches="tight")
plt.close(fig)
print("PR-04 OK")

# ================= PR-05 ELEVAÇÕES =================
fig, ax = nova_prancha(
    "PR-05 — Elevações (4 fachadas)",
    "alvenaria tijolo até 1,2 m · tela galvanizada até 3,0 m · portão 2 m na sul",
)
ax.set_xlim(-2, 30)
ax.set_ylim(-2, 16)


def elevacao(x0, y0, larg, titulo, portao=False, marcas=None):
    ax.plot([x0 - 0.5, x0 + larg + 0.5], [y0, y0], color="#8B4513", linewidth=2)
    ax.add_patch(
        patches.Rectangle(
            (x0, y0), larg, 1.2, linewidth=1.5, edgecolor="black", facecolor="#ffcc99"
        )
    )
    ax.add_patch(
        patches.Rectangle(
            (x0, y0 + 1.2),
            larg,
            1.8,
            linewidth=1.2,
            edgecolor="black",
            facecolor="#e0e0e0",
            hatch="+++",
        )
    )
    ax.plot(
        [x0 - 0.4, x0 + larg / 2, x0 + larg + 0.4],
        [y0 + 3.0, y0 + 3.9, y0 + 3.0],
        color="black",
        linewidth=1.5,
    )
    if portao:
        ax.add_patch(
            patches.Rectangle(
                (x0 + larg / 2 - 1, y0),
                2,
                2.2,
                linewidth=1.5,
                edgecolor="black",
                facecolor="white",
            )
        )
        ax.text(
            x0 + larg / 2, y0 + 1.1, "portão\n2 m", fontsize=7, ha="center", va="center"
        )
    for mx, txt in marcas or []:
        ax.text(x0 + mx, y0 + 0.6, txt, fontsize=6.5, ha="center", color="#0000cc")
    ax.text(
        x0 + larg / 2, y0 - 0.9, titulo, fontsize=10, ha="center", fontweight="bold"
    )
    ax.text(x0 + larg + 0.7, y0 + 0.6, "1,2 m", fontsize=7, ha="left", color="#666")
    ax.text(x0 + larg + 0.7, y0 + 2.1, "1,8 m", fontsize=7, ha="left", color="#666")


elevacao(1, 9, 6, "SUL (portão)", portao=True)
elevacao(10, 9, 6, "NORTE")
elevacao(1, 1, 12, "LESTE", marcas=[(6, "quadro"), (10.5, "água")])
elevacao(16, 1, 12, "OESTE (cerca Bloco N a 5,8 m)")
fig.savefig(f"{DES}/oficina-PR-05-elevacoes.png", dpi=150, bbox_inches="tight")
plt.close(fig)
print("PR-05 OK")

# ================= PR-06 ELÉTRICA =================
fig, ax = nova_prancha(
    "PR-06 — Elétrica definitiva (esquemática)",
    "220 V monofásico (padrão ENEL-CE) · tomadas por bancada · força p/ solda · aterramento — potências A CONFIRMAR",
)
ax.set_xlim(-3, 15)
ax.set_ylim(-2, 14)
ax.add_patch(
    patches.Rectangle(
        (0, 0), 6, 12, linewidth=2, edgecolor="black", facecolor="#fafafa"
    )
)
# quadro + eletrodutos
ax.add_patch(
    patches.Rectangle(
        (5.7, 6.1), 0.6, 0.6, linewidth=1.5, edgecolor="black", facecolor="#ffcdd2"
    )
)
ax.text(
    6.6,
    6.4,
    "QD\nDR",
    fontsize=7,
    ha="left",
    va="center",
    color="#cc0000",
    fontweight="bold",
)
runners = [
    ((1.5, 10.5), "T1"),
    ((4.3, 5.1), "T2"),
    ((4.5, 10.5), "T3"),
    ((1.25, 5.6), "FORÇA"),
    ((5.0, 1.5), "T4"),
]
for (tx, ty), lab in runners:
    ax.plot([6.0, tx], [6.4, ty], "--", color="#cc0000", linewidth=1)
    ax.plot(tx, ty, "o", color="#cc0000", markersize=7, zorder=5)
    ax.text(tx, ty + 0.55, lab, fontsize=7, ha="center", color="#cc0000")
# luminárias
for lx, ly in ((1.5, 3), (4.5, 3), (1.5, 9), (4.5, 9)):
    ax.plot(
        lx,
        ly,
        "o",
        color="white",
        markeredgecolor="#f9a825",
        markersize=12,
        markeredgewidth=1.5,
        zorder=5,
    )
    ax.plot(
        [lx - 0.15, lx + 0.15], [ly - 0.15, ly + 0.15], color="#f9a825", linewidth=1.2
    )
    ax.plot(
        [lx - 0.15, lx + 0.15], [ly + 0.15, ly - 0.15], color="#f9a825", linewidth=1.2
    )
ax.text(
    3,
    12.5,
    "4 luminárias LED (posição A CONFIRMAR)",
    fontsize=8,
    ha="center",
    color="#f9a825",
)
# aterramento
ax.plot([7.5, 6.8, 8.2, 7.5], [1.0, 0.0, 0.0, 1.0], color="#6a1b9a", linewidth=1.5)
ax.plot([7.5, 7.5], [1.0, 1.8], color="#6a1b9a", linewidth=1.5)
ax.text(7.5, 2.2, "aterramento\n(haste)", fontsize=8, ha="center", color="#6a1b9a")
# quadro de cargas
ax.text(
    10.5,
    9,
    "QUADRO DE CARGAS (preliminar)\n"
    "─────────────────────\n"
    "· Iluminação LED\n"
    "· T1/T2/T3 220 V (bancadas)\n"
    "· T4 220 V betoneira/externo (dedicado)\n"
    "· FORÇA p/ solda (dedicado:\n"
    "  disjuntor + bitola maiores)\n"
    "· DR geral + terra\n"
    "rede 220 V monofásica (ENEL-CE)\n"
    "potência contratada: A CONFIRMAR\n(pendência 9)",
    fontsize=9,
    ha="left",
    va="top",
    bbox=dict(boxstyle="round,pad=0.4", facecolor="#fff3e0", edgecolor="#cc0000"),
)
cotas_retangulo(ax, 0, 0, 6, 12)
fig.savefig(f"{DES}/oficina-PR-06-eletrica.png", dpi=150, bbox_inches="tight")
plt.close(fig)
print("PR-06 OK")

# ================= PR-07 HIDRÁULICA =================
fig, ax = nova_prancha(
    "PR-07 — Hidráulica (esquemática)",
    "entrada ~14,5 m (Banheiro/casa) · PVC 25 mm · torneira + lava-peças",
)
ax.set_xlim(-3, 15)
ax.set_ylim(-2, 14)
ax.add_patch(
    patches.Rectangle(
        (0, 0), 6, 12, linewidth=2, edgecolor="black", facecolor="#fafafa"
    )
)
ax.annotate(
    "",
    xy=(6.0, 1.5),
    xytext=(12.0, 8.0),
    arrowprops=dict(arrowstyle="->", color="#0288d1", lw=2, linestyle="--"),
)
ax.text(
    12.0,
    8.6,
    "Banheiro/casa\n~14,5 m",
    fontsize=9,
    ha="center",
    color="#0288d1",
    fontweight="bold",
)
ax.plot([6.0, 6.0], [1.5, 1.5], color="#0288d1", linewidth=3)
ax.plot([4.3, 6.0], [0.95, 0.95], color="#0288d1", linewidth=3)
ax.add_patch(
    patches.Rectangle(
        (4.3, 0.4), 1.4, 1.1, linewidth=1.5, edgecolor="#0288d1", facecolor="#b3e5fc"
    )
)
ax.text(
    5.0,
    0.95,
    "lava-peças",
    fontsize=8,
    ha="center",
    va="center",
    color="#01579b",
    fontweight="bold",
)
ax.plot(6.0, 1.5, "o", color="#0000cc", markersize=9, zorder=5)
ax.text(
    6.4,
    1.5,
    "torneira esfera\n+ registro",
    fontsize=8,
    ha="left",
    va="center",
    color="#0000cc",
)
ax.text(
    3,
    6,
    "PVC soldável 25 mm\n(bitola A CONFIRMAR —\nvazão pendência 11)",
    fontsize=9,
    ha="center",
    va="center",
    color="#555",
    bbox=dict(boxstyle="round,pad=0.4", facecolor="#e1f5fe", edgecolor="#0288d1"),
)
cotas_retangulo(ax, 0, 0, 6, 12)
fig.savefig(f"{DES}/oficina-PR-07-hidraulica.png", dpi=150, bbox_inches="tight")
plt.close(fig)
print("PR-07 OK")

# ================= PR-08 DETALHES =================
fig, ax = nova_prancha(
    "PR-08 — Detalhes executivos (sem escala)",
    "D1 pilar · D2 porta 1 m + janela (Depósito) · D3 bancada · D4 portão 2 m · D5 porta 2,5 m anexo",
)
ax.set_xlim(0, 32)
ax.set_ylim(0, 13)
# ---- fileira superior ----
# D1
ax.text(4, 12.4, "D1 — PILAR / SAPATA", fontsize=10, fontweight="bold", ha="center")
ax.plot([0.5, 7.5], [7.6, 7.6], color="#8B4513", linewidth=2.5)
ax.add_patch(
    patches.Rectangle(
        (3, 7.0),
        2,
        0.6,
        linewidth=1.2,
        edgecolor="black",
        facecolor="#9e9e9e",
        hatch="///",
    )
)
ax.text(4, 6.7, "sapata 50×50×30", fontsize=7, ha="center")
ax.add_patch(
    patches.Rectangle(
        (3.7, 7.6),
        0.6,
        3.6,
        linewidth=1.5,
        edgecolor="black",
        facecolor="#cfd8dc",
    )
)
ax.plot([3.85, 3.85], [7.6, 11.2], "--", color="black", linewidth=1)
ax.plot([4.15, 4.15], [7.6, 11.2], "--", color="black", linewidth=1)
ax.text(4.9, 9.4, "pilar 15×15\n+ esperas", fontsize=7, ha="left")
# D2 porta 1 m
ax.text(
    13.5,
    12.4,
    "D2 — PORTA 1 m + JANELA (Depósito)",
    fontsize=10,
    fontweight="bold",
    ha="center",
)
ax.add_patch(
    patches.Rectangle(
        (11, 7.6),
        5,
        3.6,
        linewidth=1.5,
        edgecolor="black",
        facecolor="#efebe9",
    )
)
ax.plot([13, 14], [7.6, 7.6], color="white", linewidth=5)
ax.add_patch(
    patches.Rectangle(
        (13, 7.6),
        1,
        2.8,
        linewidth=1.5,
        edgecolor="black",
        facecolor="#a1887f",
    )
)
ax.text(13.5, 9.2, "1,0 m", fontsize=7, ha="center", fontweight="bold")
ax.plot([11, 16], [10.8, 10.8], color="black", linewidth=2.5)
ax.text(13.5, 11.15, "verga + cadeado", fontsize=7, ha="center")
# D2 janela (elevação à parte)
ax.add_patch(
    patches.Rectangle(
        (17.5, 8.0),
        1.8,
        2.6,
        linewidth=1.2,
        edgecolor="black",
        facecolor="#efebe9",
    )
)
ax.add_patch(
    patches.Rectangle(
        (17.9, 9.0),
        1.0,
        1.0,
        linewidth=1.5,
        edgecolor="#0288d1",
        facecolor="#b3e5fc",
    )
)
ax.plot([17.9, 18.9], [9.5, 9.5], color="#0288d1", linewidth=2)
for gx in (18.15, 18.4, 18.65):
    ax.plot([gx, gx], [9.0, 10.0], color="#555", linewidth=1)
ax.text(18.4, 7.5, "jan. 60×60\n+ grade", fontsize=6.5, ha="center", color="#0288d1")
# D3
ax.text(27, 12.4, "D3 — BANCADA + MORSA", fontsize=10, fontweight="bold", ha="center")
ax.add_patch(
    patches.Rectangle(
        (24.5, 9.3),
        5,
        0.3,
        linewidth=1.5,
        edgecolor="black",
        facecolor="#8d6e63",
    )
)
ax.text(27, 8.9, "tampo madeira 5 cm", fontsize=7, ha="center")
ax.add_patch(
    patches.Rectangle(
        (25, 7.6),
        0.4,
        1.4,
        linewidth=1.2,
        edgecolor="black",
        facecolor="#bcaaa4",
    )
)
ax.add_patch(
    patches.Rectangle(
        (28.6, 7.6),
        0.4,
        1.4,
        linewidth=1.2,
        edgecolor="black",
        facecolor="#bcaaa4",
    )
)
ax.add_patch(
    patches.Rectangle(
        (26.4, 9.6),
        1.2,
        0.8,
        linewidth=1.5,
        edgecolor="black",
        facecolor="#78909c",
    )
)
ax.text(27, 10.0, "morsa", fontsize=7, ha="center", color="white", fontweight="bold")
# ---- fileira inferior ----
# D4 portão 2 m da oficina
ax.text(
    7,
    5.6,
    "D4 — PORTÃO 2 m (oficina, face sul)",
    fontsize=10,
    fontweight="bold",
    ha="center",
)
ax.add_patch(
    patches.Rectangle(
        (1.5, 1.2),
        11,
        3.4,
        linewidth=1.5,
        edgecolor="black",
        facecolor="#efebe9",
    )
)
ax.plot([6, 8], [1.2, 1.2], color="white", linewidth=6)
ax.plot([6, 6.7], [1.2, 2.6], color="black", linewidth=2)
ax.plot([8, 7.3], [1.2, 2.6], color="black", linewidth=2)
ax.text(7, 2.8, "2 folhas × 1,0 m", fontsize=7, ha="center", fontweight="bold")
ax.plot([1.5, 12.5], [4.0, 4.0], color="black", linewidth=2.5)
ax.text(7, 4.35, "verga (entre pilares 1,5 / 4,5)", fontsize=7, ha="center")
ax.plot(7.6, 2.0, "o", color="black", markersize=7)
ax.text(7, 0.6, "cadeado + batentes nos pilares", fontsize=7, ha="center")
# D5 porta 2,5 m do anexo
ax.text(
    23,
    5.6,
    "D5 — PORTA 2,5 m (anexo, caminhão)",
    fontsize=10,
    fontweight="bold",
    ha="center",
)
ax.add_patch(
    patches.Rectangle(
        (17, 1.2),
        12,
        3.4,
        linewidth=1.5,
        edgecolor="black",
        facecolor="#efebe9",
    )
)
ax.plot([21.5, 24], [1.2, 1.2], color="white", linewidth=6)
ax.plot([21.5, 22.2], [1.2, 2.8], color="black", linewidth=2)
ax.plot([24, 23.3], [1.2, 2.8], color="black", linewidth=2)
ax.text(
    22.75,
    3.0,
    "2 folhas reforçadas × 1,25 m",
    fontsize=7,
    ha="center",
    fontweight="bold",
)
ax.plot([17, 29], [4.0, 4.0], color="black", linewidth=2.5)
ax.text(23, 4.35, "verga", fontsize=7, ha="center")
ax.plot(23.4, 2.0, "o", color="black", markersize=7)
ax.text(23, 0.6, "vão livre p/ caçamba + cadeado", fontsize=7, ha="center")
fig.savefig(f"{DES}/oficina-PR-08-detalhes.png", dpi=150, bbox_inches="tight")
plt.close(fig)
print("PR-08 OK")

# ================= PR-09 SOLAR (croqui de implantação) =================
fig, ax = nova_prancha(
    "PR-09 — Solar: estrutura ground-mount ao norte da oficina (croqui)",
    "azimute norte · 10–15° · 5 × 330 Wp · eletrônica na oficina — coordenada exata A CONFIRMAR (pendência 6)",
)
ax.set_xlim(-20, 30)
ax.set_ylim(-70, 60)
# faixa do lote (esquemática, ~30 m de largura, N p/ cima)
ax.add_patch(
    patches.Rectangle(
        (-15, -70),
        30,
        130,
        linewidth=2,
        edgecolor="black",
        facecolor="#f1f8e9",
        alpha=0.5,
    )
)
ax.text(0, 56, "FACE NORTE do lote", fontsize=9, ha="center", fontweight="bold")
# oficina (referência)
ax.add_patch(
    patches.Rectangle(
        (-3, -46),
        6,
        16,
        linewidth=2,
        edgecolor="black",
        facecolor="#cfd8dc",
    )
)
ax.text(
    0, -38, "OFICINA\n6×16", fontsize=9, ha="center", va="center", fontweight="bold"
)
# estrutura solar (~25 m ao norte da oficina)
ax.add_patch(
    patches.Rectangle(
        (-4, -20),
        8,
        3,
        linewidth=2,
        edgecolor="#f9a825",
        facecolor="#fff3e0",
        hatch="///",
    )
)
ax.text(
    0,
    -18.5,
    "SOLAR 5×330 Wp\n~8–12 m² · N · 10–15°",
    fontsize=9,
    ha="center",
    va="center",
    fontweight="bold",
    color="#e65100",
)
# descida enterrada até o quadro da oficina
ax.plot([0, 3], [-20, -34], "--", color="#cc0000", linewidth=1.5)
ax.text(4.5, -27, "eletroduto\nenterrado", fontsize=8, ha="left", color="#cc0000")
# norte
ax.annotate("N", xy=(26, 52), fontsize=14, ha="center", fontweight="bold", color="#333")
ax.annotate(
    "",
    xy=(26, 57),
    xytext=(26, 51),
    arrowprops=dict(arrowstyle="->", color="#333", lw=2),
)
ax.text(
    0,
    -64,
    "croqui esquemático (sem escala) · KML 2026-09-27 · "
    "faixa ~40–70 m até a face norte, sem sombra da casa",
    fontsize=8,
    ha="center",
    color="#666",
    fontstyle="italic",
)
fig.savefig(f"{DES}/oficina-PR-09-solar.png", dpi=150, bbox_inches="tight")
plt.close(fig)
print("PR-09 OK")

# ================= PDF A3 =================
import matplotlib.image as mpimg

with open(f"{DES}/memorial-oficina.md", encoding="utf-8") as f:
    memorial = f.read()

with open(f"{BASE}/orcamentos/oficina-materiais.csv", encoding="utf-8") as f:
    mat = list(csv.reader(f))

# Memorial paginado: uma folha A3 comporta ~55 linhas de 9,5 pt monoespaçada;
# o que passava disso era cortado em silêncio (§9 saía fora da página).
MEM_LINHAS = 55
_ml = memorial.splitlines()
mem_paginas = [
    "\n".join(_ml[i : i + MEM_LINHAS]) for i in range(0, len(_ml), MEM_LINHAS)
]

pranchas_png = [
    ("CAPA", None),
    ("PR-01 — Locação", f"{DES}/canteiro-locacao.png"),
    ("PR-02 — Planta baixa", f"{DES}/canteiro-planta-baixa.png"),
    ("PR-03 — Fundação", f"{DES}/oficina-PR-03-fundacao.png"),
    ("PR-04 — Cobertura", f"{DES}/oficina-PR-04-cobertura.png"),
    ("PR-05 — Elevações", f"{DES}/oficina-PR-05-elevacoes.png"),
    ("PR-06 — Elétrica", f"{DES}/oficina-PR-06-eletrica.png"),
    ("PR-07 — Hidráulica", f"{DES}/oficina-PR-07-hidraulica.png"),
    ("PR-08 — Detalhes", f"{DES}/oficina-PR-08-detalhes.png"),
    ("PR-09 — Solar", f"{DES}/oficina-PR-09-solar.png"),
    *[
        (f"MEMORIAL {n}/{len(mem_paginas)}", None)
        for n in range(1, len(mem_paginas) + 1)
    ],
    ("LISTA 1/2", None),
    ("LISTA 2/2", None),
]

with PdfPages(f"{DES}/execucao-oficina.pdf") as pdf:
    for titulo, png in pranchas_png:
        fig = plt.figure(figsize=A3)
        if titulo == "CAPA":
            fig.text(
                0.5,
                0.82,
                "OFICINA DO SÍTIO — PACOTE DE EXECUÇÃO",
                fontsize=28,
                ha="center",
                fontweight="bold",
            )
            fig.text(
                0.5,
                0.75,
                "Oficina Opção A · 6,00 × 16,00 m (oficina + anexo betoneira) + "
                "Depósito 3,80 × 4,30 m · Amarelas, Camocim-CE",
                fontsize=14,
                ha="center",
                color="#555",
            )
            fig.text(
                0.12,
                0.62,
                "PR-01 Locação (cantos WGS84)\n"
                "PR-02 Planta baixa (4 zonas + pilares)\n"
                "PR-03 Fundação (radier + sapatas + dreno)\n"
                "PR-04 Cobertura (cumeeira N-S + corte)\n"
                "PR-05 Elevações (4 fachadas)\n"
                "PR-06 Elétrica definitiva (220 V monofásico)\n"
                "PR-07 Hidráulica (lava-peças)\n"
                "PR-08 Detalhes (pilar · porta 1 m · bancada ·\n"
                "  portão 2 m · porta 2,5 m anexo)\n"
                "PR-09 Solar (ground-mount ao norte)\n"
                "+ Memorial descritivo + Lista de materiais (31 itens)",
                fontsize=13,
                va="top",
            )
            fig.text(
                0.12,
                0.18,
                "Versão 1.0 · 2026-09-27 · Paulo Jamil\n"
                "PRELIMINAR — confirmar projeto estrutural (pend. 10), "
                "força da rede 220 V (pend. 9) e vazão (pend. 11)\n"
                "Fonte: projetos/canteiro-obras.md §2.4 + §12",
                fontsize=11,
                va="top",
                color="#b71c1c",
            )
        elif titulo.startswith("MEMORIAL"):
            _n = int(titulo.split()[1].split("/")[0])
            fig.text(
                0.5,
                0.94,
                f"MEMORIAL DESCRITIVO — OFICINA DO SÍTIO  ({titulo.split()[1]})",
                fontsize=18,
                ha="center",
                fontweight="bold",
            )
            fig.text(
                0.07,
                0.88,
                mem_paginas[_n - 1],
                fontsize=9.5,
                va="top",
                ha="left",
                family="monospace",
            )
        elif titulo.startswith("LISTA"):
            parte = mat[1:16] if titulo == "LISTA 1/2" else mat[16:]
            fig.text(
                0.5,
                0.94,
                f"LISTA DE MATERIAIS — {titulo}",
                fontsize=18,
                ha="center",
                fontweight="bold",
            )
            ax = fig.add_axes([0.04, 0.04, 0.92, 0.82])
            ax.axis("off")
            tab = ax.table(
                cellText=[[r[0], r[1][:52], r[2], r[3]] for r in parte],
                colLabels=["#", "Descrição", "Qtd", "Un"],
                colWidths=[0.05, 0.62, 0.13, 0.10],
                loc="center",
            )
            tab.auto_set_font_size(False)
            tab.set_fontsize(8)
            tab.scale(1, 1.35)
        else:
            img = mpimg.imread(png)
            ax = fig.add_axes([0.02, 0.06, 0.96, 0.86])
            ax.imshow(img)
            ax.axis("off")
            fig.text(0.5, 0.96, titulo, fontsize=16, ha="center", fontweight="bold")
            fig.text(
                0.5,
                0.02,
                "Oficina do Sítio · preliminar · 2026-09-27",
                fontsize=9,
                ha="center",
                color="#666",
            )
        pdf.savefig(fig)
        plt.close(fig)

print("execucao-oficina.pdf OK")
