import os

import sympy.physics.units.definitions as u
from sympy.physics.units.quantities import Quantity
from sympy.physics.units.systems.si import dimsys_SI

from mathpad.val import Val
import mathpad.dimensions as dims

HERE = os.path.dirname(__file__)

AUTOGEN_WARNING = '"WARNING: this file was automatically generated by commented code within mathpad.py, and then modified slightly"\n'

print("writing to " + f"{HERE}/units.py\nand {HERE}/constants.py")

with open(f"{HERE}/units.py", "w") as units_f, open(
    f"{HERE}/constants.py", "w"
) as constants_f:

    # top of 'units.py'
    units_f.write(AUTOGEN_WARNING)
    units_f.write("import sympy.physics.units.definitions.unit_definitions as u\n")
    units_f.write("from mathpad.physical_quantities import *\n")

    # top of 'constants.py'
    constants_f.write(AUTOGEN_WARNING)
    constants_f.write("import sympy.physics.units.definitions.unit_definitions as u\n")
    constants_f.write("from mathpad.physical_quantities import *\n")

    for name in dir(u):
        qty = getattr(u, name)

        if name.endswith("constant"):
            constants_f.write(
                f"""
{name} = OutputVal(u.{name})"""
            )

        elif isinstance(qty, Quantity):

            for quantity_cls_name in dir(dims):
                if quantity_cls_name in "du":
                    continue

                quantity_cls = getattr(dims, quantity_cls_name)

                # handle the Angle dimension specially
                if str(qty).startswith("angular") or str(qty).startswith("rad"):
                    units_f.write(
                        f"""
{name} = Angle(u.{name})"""
                    )
                    break

                elif (
                    isinstance(quantity_cls, type)
                    and issubclass(quantity_cls, Val)
                    and quantity_cls is not Val
                    and dimsys_SI.equivalent_dims(qty.dimension, quantity_cls.dimension)
                ):
                    units_f.write(
                        f"""
{name} = {quantity_cls_name}(u.{name})"""
                    )
                    break
            else:
                print(f"Warning: Quantity '{name}' could not be matched; skipping...")
