import argparse
import sys
import os
from .conversion import parse_raw, convert_to_cim, metadata_for_raw_source
from .cim_pydantic.base import serialize_to_turtle, deserialize_from_turtle

def main():
    parser = argparse.ArgumentParser(description="Convert IEEE RAW power system models to CIM RDF (Turtle).")
    parser.add_argument("input", help="Path to the input .raw file")
    parser.add_argument("output", help="Path to the output .ttl file")
    parser.add_argument("--validate", action="store_true", help="Run round-trip validation after conversion")
    
    args = parser.parse_args()
    
    if not os.path.exists(args.input):
        print(f"Error: Input file {args.input} not found.")
        sys.exit(1)
        
    print(f"Parsing RAW file: {args.input}")
    raw_data = parse_raw(args.input)
    
    print("Converting to CIM objects...")
    cim_objects = convert_to_cim(raw_data)
    
    print(f"Serializing to Turtle: {args.output}")
    turtle_data = serialize_to_turtle(cim_objects, metadata=metadata_for_raw_source(args.input))
    
    with open(args.output, "w") as f:
        f.write(turtle_data)
        
    print(f"Exported {len(cim_objects)} objects to {args.output}")
    
    if args.validate:
        print("Running round-trip validation...")
        objects2 = deserialize_from_turtle(turtle_data)
        print(f"Deserialized {len(objects2)} objects back.")
        if len(cim_objects) == len(objects2):
            print("SUCCESS: Object counts match!")
        else:
            print(f"WARNING: Object counts differ! Original: {len(cim_objects)}, Deserialized: {len(objects2)}")

if __name__ == "__main__":
    main()
