"""LLM이 생성한 openpyxl builder 코드를 실행해 XLSX 생성.

usage: python run_xlsx_builder.py <builder.py> <data.json> <out.xlsx>

builder 코드는 모듈 레벨에서 `def build(wb, pages):` 를 정의해야 한다.
- wb: openpyxl.Workbook (기본 시트 1개 포함)
- pages: [view, view, ...] (페이지당 1시트 권장)
"""
from __future__ import annotations

import json
import sys
from pathlib import Path

from openpyxl import Workbook


def main() -> int:
    if len(sys.argv) != 4:
        print("usage: python run_xlsx_builder.py <builder.py> <data.json> <out.xlsx>", file=sys.stderr)
        return 2
    builder_path, data_path, out_path = sys.argv[1], sys.argv[2], sys.argv[3]
    try:
        code = Path(builder_path).read_text(encoding="utf-8")
        parsed = json.loads(Path(data_path).read_text(encoding="utf-8"))
        pages = parsed.get("pages") if isinstance(parsed, dict) and "pages" in parsed else [parsed]

        ns: dict = {}
        exec(compile(code, builder_path, "exec"), ns)  # noqa: S102 — 하네스 격리 실행
        build = ns.get("build")
        if not callable(build):
            raise RuntimeError("builder 코드가 build(wb, pages) 함수를 정의하지 않았습니다.")

        wb = Workbook()
        build(wb, pages)
        wb.save(out_path)
        print("XLSX_OK " + out_path)
        return 0
    except Exception as e:  # noqa: BLE001
        import traceback
        print("XLSX_FAIL " + "".join(traceback.format_exception(e)), file=sys.stderr)
        return 1


if __name__ == "__main__":
    raise SystemExit(main())
