"""Prepare a mesh-only derivative; never runs an FEMM calculation."""
from pathlib import Path
import hashlib
import json

folder = Path(__file__).resolve().parent
original = folder / "mytransformer.fem"
data = original.read_bytes()
lines = data.decode("ascii").splitlines(keepends=True)
section = None
remaining = 0
changes = []
for index, line in enumerate(lines):
    if line.startswith("[NumBlockLabels]"):
        section = "blocks"
        remaining = int(line.split("=")[1])
        continue
    if line.startswith("[NumArcSegments]"):
        section = "arcs"
        remaining = int(line.split("=")[1])
        continue
    if line.startswith("["):
        section = None
        remaining = 0
    if remaining:
        fields = line.split()
        old = fields[:]
        if section == "blocks":
            # On-disk field 4 is linear meshSize, not triangle MaxArea.
            # Native mi_setblockprop(..., 0.025, ...) -> saved field 0.025 was
            # verified in mesh_unit_probe.fem before creating this derivative.
            fields[3] = "0.025"
        elif section == "arcs":
            # Refine original ten-degree arc discretization fourfold.
            fields[3] = "2.5"
        lines[index] = "\t".join(fields) + "\r\n"
        changes.append({"line": index + 1, "section": section,
                        "old": old, "new": fields})
        remaining -= 1

assert len([c for c in changes if c["section"] == "blocks"]) == 10
assert len([c for c in changes if c["section"] == "arcs"]) == 8
assert all(c["old"][:3] == c["new"][:3] and
           c["old"][4:] == c["new"][4:] for c in changes)
refined = folder / "mytransformer_refined.fem"
refined.write_bytes("".join(lines).encode("ascii"))
manifest = {
    "original_source_url": "https://www.femm.info/examples/mytransformer/mytransformer.zip",
    "lesson_url": "https://www.femm.info/doku/doku.php?id=MyTransformer",
    "original_sha256": hashlib.sha256(data).hexdigest(),
    "refined_sha256": hashlib.sha256(refined.read_bytes()).hexdigest(),
    "unchanged": "All coordinates, materials/BH, winding signs/turns, circuits, frequency, depth, precision, minimum angle, boundaries and straight segments.",
    "refinement": "Six winding/core block mesh sizes: 0.2 to 0.025 inches. Four air blocks: automatic to 0.025 inches. Eight arc segments: 10 to 2.5 degrees. Actual node/element counts and area statistics measured, not assumed fourfold.",
    "mesh_units_evidence": "Native FEMM 5 mi_setblockprop meshSize=0.025 saved field4=0.025000000000000001; mesh_unit_probe.py/.fem/.log. The official magnetics-file-formats PDF also calls field4 meshSize and defines maximum triangular area pi*meshSize^2/4.",
    "changes": changes,
}
(folder / "mesh_derivation.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
print("Wrote mesh-only refinement:", refined)
