#!/usr/bin/env python3
"""Extract cylindrical cross-section samples from the original ring."""

from __future__ import annotations

import json
import math
import sys
from pathlib import Path

import bpy


def main() -> None:
    args = sys.argv[sys.argv.index("--") + 1 :]
    source = Path(args[0]).resolve()
    output = Path(args[1]).resolve()
    output.parent.mkdir(parents=True, exist_ok=True)
    bpy.ops.import_scene.gltf(filepath=str(source))
    obj = max((item for item in bpy.context.scene.objects if item.type == "MESH"), key=lambda item: len(item.data.vertices))
    samples = []
    for vertex in obj.data.vertices:
        point = obj.matrix_world @ vertex.co
        theta = math.degrees(math.atan2(point.y, point.x))
        samples.append((theta, math.hypot(point.x, point.y), point.z))

    section_angles = [-180, -150, -130, -115, -105, -98, -92, -88, -82, -75, -65, -50, -30, 0, 45, 90, 135]
    half_width = 0.35
    result = {"source": str(source), "sections": {}}
    for angle in section_angles:
        values = []
        for theta, radius, z in samples:
            delta = abs((theta - angle + 180.0) % 360.0 - 180.0)
            if delta <= half_width:
                values.append([round(radius, 7), round(z, 7)])
        result["sections"][str(angle)] = values
    output.write_text(json.dumps(result), encoding="utf-8")
    print("TN_SECTIONS", output, sum(len(v) for v in result["sections"].values()))


if __name__ == "__main__":
    main()
