# debugging.py: the lesson's three debugging habits as code that runs: print as you go, catch the error and see where it
# came from, and check the inputs before you build. Needs gear.py in FOLDER (it is loaded if it is not yet).
# Run: exec(open('/your/folder/debugging.py').read())     Tested in FreeCAD 1.1.4.
import os, time, traceback
import Part
FOLDER = os.path.expanduser('~/gear-scripts')        # the folder where you saved gear.py: put its full path here
FOLDER = os.environ.get('PS_SCRIPTS', FOLDER)          # (a PS_SCRIPTS setting wins: used by the tests)
if 'create_involute_gear' not in globals():
    g = {'__name__': 'gear'}; exec(open(os.path.join(FOLDER, 'gear.py')).read(), g)
    create_involute_gear = g['create_involute_gear']

# 1. Print as you go: say what is about to happen and how long it took.
print("Starting gear generation...")
t0 = time.perf_counter()
gear = create_involute_gear(module=2.5, num_teeth=24)
print("  done in %.2f s: %d faces, %d edges, volume %.0f mm3" % (time.perf_counter() - t0, len(gear.Faces), len(gear.Edges), gear.Volume))

# 2. Catch the error, print it and where it came from, and carry on.
caught = []
for args in ({'module': 2.5, 'num_teeth': 24}, {'module': -1, 'num_teeth': 24}):
    try:
        Part.show(create_involute_gear(**args), "Gear")
        print("  built", args)
    except Exception as e:
        caught.append(e)
        print("  Error occurred:", e)
        traceback.print_exc()          # the full trace: file, line, and the call that failed

# 3. Check the inputs first: create_involute_gear() refuses a module of 0 or under 4 teeth before it draws anything.
for bad in ({'module': 0, 'num_teeth': 24}, {'module': 2.5, 'num_teeth': 2}):
    try:
        create_involute_gear(**bad)
    except ValueError as e:
        caught.append(e); print("  refused", bad, "->", e)

# ---- test
assert len(caught) == 3 and all(isinstance(e, ValueError) for e in caught)
print("TEST debugging.py: PASS")
