import argparse
import sys
from pathlib import Path
from altrus.core.kernel import AltrusKernel

def run_demo():
    try:
        from examples import demo_scenarios
        demo_scenarios.main()
    except ImportError:
        import sys
        from pathlib import Path
        repo_root = Path(__file__).resolve().parent.parent.parent
        sys.path.append(str(repo_root))
        from examples import demo_scenarios
        demo_scenarios.main()

def main():
    parser = argparse.ArgumentParser(description="ALTRUS: Fault-Tolerant Intent-Driven Middleware for Modular Robots")
    parser.add_argument("--version", action="version", version="altrus 0.1.12")

    subparsers = parser.add_subparsers(dest="command", help="Available commands")

    # Start command
    start_parser = subparsers.add_parser("start", help="Start the ALTRUS kernel")
    start_parser.add_argument("--config", type=str, help="Path to configuration file")

    # Demo command
    demo_parser = subparsers.add_parser("demo", help="Run system demonstration scenarios")

    args = parser.parse_args()

    if args.command == "start":
        print("Starting ALTRUS Kernel...")
        config_path = Path(args.config) if args.config else None
        kernel = AltrusKernel(config_path=config_path)
        kernel.start()
        print(f"Kernel started in state: {kernel.get_system_state().value}")
        try:
            # Keep the kernel running if needed, or just demonstrate start/stop
            print("Press Ctrl+C to shutdown.")
            import time
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            kernel.shutdown("User interrupted")
            print("Kernel shutdown complete.")

    elif args.command == "demo":
        print("Running ALTRUS Demonstrations...")
        run_demo()

    else:
        parser.print_help()

if __name__ == "__main__":
    main()
