"""
This script generates a stub file for the qcconst.constants module so that
it can be used with type checkers like mypy. It imports the module, extracts
the constants, and writes them to a .pyi file with appropriate type annotations.
"""

import importlib
import sys
import textwrap
from pathlib import Path

# Ensure the script can import the qcconst module even though it is not installed in
# the current environment.
ROOT = Path(__file__).resolve().parent.parent  # qcconst root
SRC = ROOT / "src"
sys.path.insert(0, str(SRC))  # ← now import works

mod = importlib.import_module("qcconst.constants")  # triggers _load_constants

PKG = "qcconst.constants"
mod = importlib.import_module(PKG)

header = textwrap.dedent(
    """\
    # Auto-generated by build_tools/gen_stubs.py - DO NOT EDIT BY HAND
    from typing import Dict, Final

    from qcconst.models import Value
    """
)
body = "\n".join(
    f"{name}: Final[Value]"
    for name, value in vars(mod).items()
    if name.isupper() and not name.startswith("_")
)

codata = "\n".join(
    f"{name}: Dict[str, Value]"
    for name, value in vars(mod).items()
    if name.startswith("codata")
    and not name.startswith("_")
    or name.startswith("phys")
    and not name.startswith("_")
)

stub = Path(mod.__file__).with_suffix(".pyi")  # type: ignore
stub.write_text(header + "\n" + body + "\n" + codata + "\n", encoding="utf-8")
