"""
NX Journal to verify if expressions are linked to geometry

This journal will:
1. Open Bracket.prt
2. Print current expression values
3. Print geometry bounding box / feature parameters
4. Check if expressions control any features
"""

import NXOpen
import sys

def main(args):
    theSession = NXOpen.Session.GetSession()

    # Open Bracket.prt
    prt_file = r"C:\Users\antoi\Documents\Atomaste\Atomizer\examples\bracket\Bracket.prt"
    print(f"Opening {prt_file}...")

    try:
        basePart, partLoadStatus = theSession.Parts.OpenActiveDisplay(
            prt_file,
            NXOpen.DisplayPartOption.AllowAdditional
        )
        partLoadStatus.Dispose()

        workPart = theSession.Parts.Work

        print("\n" + "="*60)
        print("EXPRESSION VALUES:")
        print("="*60)

        # Get expressions
        tip_thickness = workPart.Expressions.FindObject("tip_thickness")
        support_angle = workPart.Expressions.FindObject("support_angle")

        if tip_thickness:
            print(f"tip_thickness = {tip_thickness.Value}")
        else:
            print("ERROR: tip_thickness expression not found!")

        if support_angle:
            print(f"support_angle = {support_angle.Value}")
        else:
            print("ERROR: support_angle expression not found!")

        print("\n" + "="*60)
        print("CHECKING FEATURE DEPENDENCIES:")
        print("="*60)

        # Check if any features reference these expressions
        features = workPart.Features
        for feature in features:
            try:
                # Get feature parameters
                params = feature.GetFeatureParameters()
                for param in params:
                    try:
                        # Check if parameter uses our expressions
                        expr = param.RightHandSide
                        if expr and hasattr(expr, 'Name'):
                            if 'tip_thickness' in expr.Name or 'support_angle' in expr.Name:
                                print(f"  Feature '{feature.Name}' uses expression '{expr.Name}'")
                    except:
                        pass
            except:
                pass

        print("\n" + "="*60)
        print("PART BOUNDING BOX:")
        print("="*60)

        # Get bounding box (shows overall geometry size)
        try:
            bodies = workPart.Bodies
            if bodies and len(bodies) > 0:
                body = bodies[0]
                # Get bounding box
                corner1 = [0.0, 0.0, 0.0]
                directions = [[0.0]*3, [0.0]*3, [0.0]*3]
                distances = [0.0, 0.0, 0.0]

                theUfSession = NXOpen.UF.UFSession.GetUFSession()
                theUfSession.Modl.AskBoundingBoxExact(body.Tag, corner1, directions, distances)

                print(f"  X extent: {distances[0]:.2f}")
                print(f"  Y extent: {distances[1]:.2f}")
                print(f"  Z extent: {distances[2]:.2f}")
        except Exception as e:
            print(f"  Could not get bounding box: {e}")

        print("\n" + "="*60)
        print("ALL EXPRESSIONS IN PART:")
        print("="*60)

        # List all expressions
        for expr in workPart.Expressions:
            print(f"  {expr.Name} = {expr.Value} (units: {expr.Units if hasattr(expr, 'Units') else 'N/A'})")

        print("\n" + "="*60)
        print("Done!")

        return True

    except Exception as e:
        print(f"ERROR: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == '__main__':
    success = main(sys.argv[1:])
    sys.exit(0 if success else 1)
