#!/usr/bin/env python3
# SPDX-License-Identifier: LGPL-3.0-or-later
# Copyright (C) 2026 Pranay Kiran
"""A downloaded 3D CAD model to a checked fabrication drawing, in one run.

    python3 make_drawing.py

What it does, in the five stages the pipeline ships as slash commands:

    1  /analyse   headless FreeCAD reads the model: bodies, sketches,
                  materials, what the file shows when it opens
    2  /judge     is the model ready to draft? thin features at the sheet
                  scale, missing material, anything hidden
    3  /finalise  the DECISIONS below — the only hand-written input — are
                  checked and LOCKED into a manifest
    4  /draw      the sheet is composed and written as Musa CAD native
                  .musa, then read BACK twice: the value check (does the
                  sheet print what the manifest states?) and the layout
                  check (do the leaders, dimensions and labels read?)
    5  /export    plotted to PDF, with the plotted scale cross-checked

Nothing here is drawn by hand. Every view, dimension line, leader, hatch
and title-block field is placed by the engine and then audited on the
finished sheet.

The model is a stock SHF08 shaft holder from the FreeCAD Parts Library
(CC BY 3.0). The fits, finishes and notes on the sheet are illustrative:
this is a drafting demonstration, not a released part.
"""
from __future__ import annotations

import json
import os
import shutil
import subprocess
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
PIPELINE = Path(os.environ.get("FABPIPE", HERE / "fabrication_pipeline"))
MODEL = HERE / "model" / "SHF08.FCStd"
TEMPLATE = HERE / "template" / "template_musacad.musa"
OUT = HERE / "out"
# Musa CAD itself, to prove the sheet is an ordinary .musa: the AppImage
# from musacad.org, or whatever `musacad` is on PATH.
MUSACAD = os.environ.get(
    "MUSACAD", "musacad")

# --------------------------------------------------------------------
# THE DECISIONS. A draughtsman makes these; the engine does the rest.
# Coordinates are the part's own millimetres in the view they name, which
# is how the model measures: the bore axis is (0, 0) in the front view.
# --------------------------------------------------------------------
PART = {
    "part_id": "01",
    "file": str(MODEL),
    "description": "SHAFT HOLDER SHF08",
    "drg_no": "MC-SHF08-01",
    "material": "ALUMINIUM 6061-T6",
    "qty": 1,
    "sheet": True,
    # look along the bore: the outline, both mounting holes and the clamp
    # slot are all in one view
    "front_view": "+Y",
    # ... and cut through the bore axis, so the section shows the bore and
    # the mounting holes at their true diameters (0.583 of the 24 mm
    # height, measured from the bottom of the view)
    "section": {"enabled": True, "projection": "below",
                "offset_frac": 0.5833, "label": "A"},
    "scale": "2:1",
    # no shaded pictorial: the pipeline stamps that as a raster at plot
    # time, and this sheet is meant to plot identically under Musa CAD's
    # own `--plot`, which stamps none
    "pictorial": False,
    # the ends are full radii, so the overall width is a tangent point
    # nobody can measure: the part is dimensioned by its features instead
    "front_extent_dims": False,
    # each arrow lands on the side of its feature the callout column is
    # on, so no leader has to cross the view to reach its note
    "callouts": [
        # the bore's fit is called out on the SECTION, where its depth
        # is what the reader is looking at
        {"view": "section", "at": [4.0, 7.0], "circle_r": 4.0,
         "text": "%%c8 H7 (+0.015/0)"},
        # the chamfer mouth is a circle of its own: this callout speaks
        # for it too (`suppress_radii`), so it is not dimensioned twice
        {"view": "front", "at": [18.19, 1.94], "circle_r": 2.75,
         "suppress_dia_dim": True, "suppress_radii": [3.5],
         "text": "2X %%c5.5 THRU"},
        {"view": "front", "at": [9.5, -13.0], "text": "%%c4 THRU"},
    ],
    "location_dims": [
        # mounting hole pitch — BASIC, because the position frame below
        # is what controls it (ASME Y14.5)
        {"view": "front", "orient": "h", "side": "top", "basic": True,
         "a": [-16.25, 0.0], "b": [16.25, 0.0]},
        # overall height on one side; the two heights that locate the
        # bore and the clamp screw above the base on the other
        {"view": "front", "orient": "v", "side": "left",
         "a": [0.0, 10.0], "b": [0.0, -14.0]},
        {"view": "front", "orient": "v", "side": "right",
         "a": [0.0, 0.0], "b": [0.0, -14.0]},
        {"view": "front", "orient": "v", "side": "right",
         "a": [0.0, -11.0], "b": [0.0, -14.0]},
        # the clamp lugs and the slot between them
        {"view": "front", "orient": "h", "side": "bottom",
         "a": [-10.0, -14.0], "b": [10.0, -14.0]},
        {"view": "front", "orient": "h", "side": "bottom",
         "a": [-0.6, -14.0], "b": [0.6, -14.0]},
    ],
    "gdt": {
        "datums": [{"label": "A", "view": "section",
                    "target": "bottom_face"}],
        "frames": [
            {"symbol": "perpendicularity", "view": "section",
             "target": "bore_r4", "tol": "0.05", "refs": ["A"]},
            {"symbol": "position", "view": "front",
             "target": "hole_r2.75", "tol": "0.2", "refs": ["A"]},
        ],
    },
    "fab_notes": [
        "DATUM A IS THE MOUNTING FACE.",
        "BOTH ENDS R5.25 ABOUT THE %%c5.5 HOLE CENTRES.",
        "THE %%c4 CROSS HOLE TAKES THE M4 CLAMP SCREW.",
        "CHAMFER 0.75 x 45%%d BOTH ENDS OF EACH %%c5.5 HOLE; "
        "0.2 x 45%%d BOTH ENDS OF THE BORE.",
        "BORE Ra 1.6; ALL OTHER MACHINED SURFACES Ra 3.2.",
        "BREAK ALL SHARP EDGES 0.2-0.5 x 45%%d.",
        "MODEL: SHF08, FREECAD PARTS LIBRARY, CC BY 3.0.",
    ],
    # the model carries no material, which /judge reports; the manifest
    # states one, and the waiver records that the decision was taken
    "waivers": ["material undefined (FreeCAD 'Default') — title block "
                "MATERIAL will need a value at /finalise"],
}

DECISIONS = {
    "locked": False,
    "project": "MUSA CAD DEMONSTRATION",
    "drg_no_prefix": "MC",
    "drawn_by": "MUSA CAD",
    "rev": "00",
    "model_dir": str(MODEL.parent),
    "assembly_file": "",
    # a company title block is a PROJECT file: the pipeline ships one
    # sheet layout and this points at our own copy of it
    "template": str(TEMPLATE),
    "parts": [PART],
    "assembly_sheet": {"enabled": False},
}


def drawing_window(sheet: dict) -> tuple:
    """The window that holds the DRAWING and nothing else.

    A pipeline sheet is a sheet: title block, revision table and parts
    row around a drawing area. For a page about the drawing, plot the
    ink inside that area — the views, their dimensions and the notes —
    and leave the furniture out. The area is the template's own, and the
    layout check guarantees nothing was placed outside it. The parts row
    stands along the bottom of that area, so the floor goes above it."""
    sys.path.insert(0, str(PIPELINE / "src"))
    import draw                                   # noqa: PLC0415
    import layout_check as lc                     # noqa: PLC0415
    import musa_writer as mw                      # noqa: PLC0415

    m = json.loads((OUT / "manifest.json").read_text())
    mw.use_template(mw.resolve_template(m["template"]))
    num, den = (int(v) for v in sheet["scale"].split(":"))
    ctx = draw.sheet_context(m, m["parts"][0], num, den)
    edge = 0.6                       # the furniture's own rules sit here
    floor = draw.table_band(ctx, mw.PARTS_ROW_H * ctx.t)[3]
    ax0, ay0, ax1, ay1 = (ctx.draw_area[0] + edge, floor + edge,
                          ctx.draw_area[2] - edge, ctx.draw_area[3] - edge)
    text = (OUT / "MC-SHF08-01.musa").read_text()
    recs = lc.parse(text)
    runs = []                        # every run of ink, as point lists
    for r in recs:
        if r.kind in ("LINE", "POLYLINE", "ARC", "CIRCLE", "HATCH"):
            runs.append([p for seg in lc.segments(r) for p in seg])
        elif r.kind in lc.TEXT_KINDS:
            ink = lc.text_ink(r)
            if ink:
                runs.append([(ink[0], ink[1]), (ink[2], ink[3])])
    # a DIM draws its own lines at plot time; layout_check rebuilds them
    # exactly as MusaCAD does, which is what has to be inside the window
    lfacs = lc.dim_styles(text)[1]
    for group in lc.dim_ink(recs, lfacs=lfacs):
        runs += [[a, b] for a, b, _name in group]
    lo, hi = [1e9, 1e9], [-1e9, -1e9]
    for pts in runs:
        if not pts or not all(ax0 <= x <= ax1 and ay0 <= y <= ay1
                              for x, y in pts):
            continue                 # furniture, or ink of the sheet
        for x, y in pts:
            lo = [min(lo[0], x), min(lo[1], y)]
            hi = [max(hi[0], x), max(hi[1], y)]
    pad = 1.0
    return (max(ax0, lo[0] - pad), max(ay0, lo[1] - pad),
            min(ax1, hi[0] + pad), min(ay1, hi[1] + pad))


def run(*args: str, stage: str) -> str:
    """One pipeline stage, in its own clone."""
    print(f"\n=== {stage}\n$ {' '.join(args)}")
    done = subprocess.run(args, cwd=PIPELINE, text=True,
                          capture_output=True)
    out = (done.stdout or "") + (done.stderr or "")
    print(out.rstrip()[-2000:])
    if done.returncode != 0:
        sys.exit(f"{stage} failed ({done.returncode})")
    return out


def main() -> None:
    if not MODEL.exists():
        sys.exit(f"no model at {MODEL} — see README.md for the download")
    if not (PIPELINE / "src" / "draw.py").exists():
        sys.exit(f"no pipeline at {PIPELINE} — see README.md")
    py = sys.executable

    run(py, "src/analyse.py", str(MODEL.parent), "--no-assembly",
        "--parts", str(MODEL), stage="1/5  /analyse — read the model")
    run(py, "src/judge.py", stage="2/5  /judge — is it ready to draft?")

    draft = PIPELINE / "manifests" / "demo_draft.json"
    draft.parent.mkdir(parents=True, exist_ok=True)
    draft.write_text(json.dumps(DECISIONS, indent=1))
    run(py, "src/manifest.py", "lock", str(draft),
        stage="3/5  /finalise — check and lock the decisions")

    run(py, "src/draw.py",
        stage="4/5  /draw — compose the sheet, then read it back twice")
    run(py, "src/export.py", stage="5/5  /export — plot it")

    OUT.mkdir(exist_ok=True)
    for src in [PIPELINE / "output" / "musa" / "MC-SHF08-01.musa",
                PIPELINE / "output" / "pdf" / "MC-SHF08-01.pdf",
                PIPELINE / "output" / "musa" / "sheets.json",
                PIPELINE / "reports" / "analysis.json",
                PIPELINE / "reports" / "judgement.md",
                PIPELINE / "manifests" / "manifest.json"]:
        if src.exists():
            shutil.copy2(src, OUT / src.name)

    # The same file, plotted by Musa CAD itself. The pipeline writes plain
    # .musa, so the product reads it without knowing where it came from —
    # twice: the whole sheet, and the DRAWING on its own (the window is
    # the drawing area, so the title block and the parts row stay out of
    # the picture), which is the one to put on a page.
    musa = Path(MUSACAD)
    if musa.exists() or shutil.which(str(musa)):
        sheet = json.loads((OUT / "sheets.json").read_text())["sheets"][0]
        for name, win in (("MC-SHF08-01-musacad", sheet["window"]),
                          ("MC-SHF08-01-drawing", drawing_window(sheet))):
            done = subprocess.run(
                [str(musa), "--plot", str(OUT / "MC-SHF08-01.musa"),
                 str(OUT / f"{name}.pdf"),
                 "--paper", sheet["paper"],
                 "--landscape" if name.endswith("drawing")
                 else f"--{sheet['orientation']}",
                 "--scale", sheet["scale"],
                 "--window", ",".join(f"{v:.3f}" for v in win)],
                text=True, capture_output=True,
                env={**os.environ, "QT_QPA_PLATFORM": "offscreen"})
            print(f"\n=== plotted by Musa CAD itself: {name}.pdf\n"
                  f"{(done.stdout or done.stderr).strip()[:300]}")

    print(f"\nwrote {OUT}")


if __name__ == "__main__":
    main()
