"""
Alyios Automation Framework - Professional Examples
Demonstrates the power of the automation system
"""

from alyios_windows import automation, select_option, notifications
import time


def example_1_manual_script():
    """Example 1: Create and play a script manually"""
    print("\n" + "="*60)
    print("EXAMPLE 1: Manual Script Creation")
    print("="*60)

    # Create a new script
    script = automation.create_script("Demo Script")
    script.description = "Demonstrates basic automation"

    # Add actions programmatically
    script.add_action(automation.ClickAction(500, 300, button='left'))
    script.add_action(automation.DelayAction(500))
    script.add_action(automation.TypeAction("Hello from Alyios!"))
    script.add_action(automation.DelayAction(500))
    script.add_action(automation.KeyAction('enter'))

    print(f"Created script with {len(script)} actions")
    print("\nActions:")
    for i, action in enumerate(script.actions, 1):
        print(f"  {i}. {action}")

    # Save the script
    script.save("demo_script.json")
    print("\nScript saved to: demo_script.json")

    # Export to Python
    python_code = script.export_to_python("demo_script.py")
    print("\nExported to Python:")
    print("-" * 60)
    print(python_code[:400] + "...")

    print("\n[!] Script created but not played (would automate your system)")


def example_2_record_playback():
    """Example 2: Record and playback"""
    print("\n" + "="*60)
    print("EXAMPLE 2: Record & Playback")
    print("="*60)

    choice = select_option(
        "What would you like to do?",
        ["Record a new script", "Load and play existing script", "Skip"]
    )

    if choice == "Record a new script":
        print("\nStarting recorder...")
        print("Click anywhere 3 times, then press Enter to stop")

        recorder = automation.record("My Recording")

        # Wait for user to click 3 times
        time.sleep(0.5)
        print("Recording... (make some clicks!)")
        input("\nPress Enter when done recording...")

        script = recorder.stop()
        print(f"\nRecorded {len(script)} actions!")

        # Save it
        script.save("my_recording.json")
        print("Saved to: my_recording.json")

        # Ask if they want to play it back
        if select_option("Play it back?", ["Yes", "No"]) == "Yes":
            print("\nPlaying in 3 seconds...")
            time.sleep(3)
            script.play()
            print("Playback complete!")

    elif choice == "Load and play existing script":
        try:
            script = automation.load_script("demo_script.json")
            print(f"\nLoaded: {script.name}")
            print(f"Actions: {len(script)}")

            if select_option("Play this script?", ["Yes", "No"]) == "Yes":
                print("\nPlaying in 3 seconds...")
                time.sleep(3)
                script.play()
                print("Complete!")
        except FileNotFoundError:
            print("\nNo demo_script.json found. Run Example 1 first!")


def example_3_variables():
    """Example 3: Using variables in automation"""
    print("\n" + "="*60)
    print("EXAMPLE 3: Variables & Dynamic Content")
    print("="*60)

    script = automation.create_script("Variable Demo")

    # Set a variable
    script.add_action(automation.SetVariableAction("username", "JohnDoe"))
    script.add_action(automation.SetVariableAction("email", "john@example.com"))

    # Use variables in typing (using {variable_name} syntax)
    script.add_action(automation.TypeAction("Username: {username}"))
    script.add_action(automation.KeyAction('enter'))
    script.add_action(automation.TypeAction("Email: {email}"))

    print("Script with variables:")
    for i, action in enumerate(script.actions, 1):
        print(f"  {i}. {action}")

    # Show Python export
    print("\nPython export:")
    print("-" * 60)
    print(script.export_to_python())


def example_4_advanced_features():
    """Example 4: Advanced automation features"""
    print("\n" + "="*60)
    print("EXAMPLE 4: Advanced Features")
    print("="*60)

    script = automation.create_script("Advanced Demo")

    # Multiple actions
    actions = [
        automation.ClickAction(100, 100),
        automation.DelayAction(200),
        automation.KeyAction('ctrl', modifiers=['ctrl']),
        automation.TypeAction("Advanced automation"),
        automation.DelayAction(500),
        automation.ScreenshotAction("automation_screenshot.png"),
        automation.KeyAction('enter'),
    ]

    for action in actions:
        script.add_action(action)

    print(f"Created script with {len(script)} actions")

    # Demonstrate different playback speeds
    print("\nPlayback speed options:")
    print("  - Normal speed (1.0x)")
    print("  - Fast (2.0x)")
    print("  - Slow (0.5x)")

    # Demonstrate looping
    print("\nLoop options:")
    print("  - Run once")
    print("  - Loop 5 times")
    print("  - Loop 10 times")

    print("\nExample: script.play(loop_count=5, speed=2.0)")


def example_5_integration():
    """Example 5: Integration with other modules"""
    print("\n" + "="*60)
    print("EXAMPLE 5: Integration with Clipboard, Screen, etc.")
    print("="*60)

    from alyios_windows import clipboard, screen, notifications as notif

    script = automation.create_script("Integrated Demo")

    print("This script will:")
    print("  1. Get text from clipboard")
    print("  2. Take a screenshot")
    print("  3. Show a notification")
    print("  4. Type the clipboard content")

    # You can mix automation with direct function calls
    print("\nExample workflow:")
    print("  clipboard_text = clipboard.get_text()")
    print("  screen.screenshot('before.png')")
    print("  notif.toast('Starting automation!')")
    print("  script.play()")
    print("  screen.screenshot('after.png')")


def example_6_script_editing():
    """Example 6: Edit and modify scripts"""
    print("\n" + "="*60)
    print("EXAMPLE 6: Script Editing")
    print("="*60)

    script = automation.create_script("Editable Script")

    # Add some actions
    script.add_action(automation.ClickAction(100, 100))
    script.add_action(automation.TypeAction("Original text"))
    script.add_action(automation.DelayAction(1000))

    print("Original script:")
    for i, action in enumerate(script.actions):
        print(f"  {i}. {action}")

    # Modify an action
    print("\nModifying action 1...")
    script.actions[1].properties['text'] = "Modified text!"

    # Remove an action
    print("Removing action 2 (delay)...")
    script.remove_action(2)

    # Add a new action
    print("Adding new action...")
    script.add_action(automation.KeyAction('enter'))

    print("\nModified script:")
    for i, action in enumerate(script.actions):
        print(f"  {i}. {action}")

    # Save different versions
    script.save("script_v1.json")
    print("\nSaved as: script_v1.json")


def main():
    """Main demo menu"""
    print("""
    ╔══════════════════════════════════════════════════════════╗
    ║                                                          ║
    ║    Alyios Automation Framework - Professional Edition   ║
    ║                                                          ║
    ║    Power Automate-level automation for Python!          ║
    ║                                                          ║
    ╚══════════════════════════════════════════════════════════╝
    """)

    examples = {
        "1. Manual Script Creation": example_1_manual_script,
        "2. Record & Playback": example_2_record_playback,
        "3. Variables & Dynamic Content": example_3_variables,
        "4. Advanced Features": example_4_advanced_features,
        "5. Integration with Other Modules": example_5_integration,
        "6. Script Editing": example_6_script_editing,
        "Run All Examples": None,
        "Exit": None
    }

    while True:
        print("\n" + "="*60)
        choice = select_option("Select an example:", list(examples.keys()))

        if choice == "Exit":
            print("\nThank you for exploring Alyios Automation!")
            break
        elif choice == "Run All Examples":
            for name, func in examples.items():
                if func and name != "Run All Examples":
                    func()
                    input("\nPress Enter for next example...")
        else:
            examples[choice]()

        print("\n" + "="*60)
        input("Press Enter to continue...")


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n\nExiting...")
    except Exception as e:
        print(f"\n\nError: {e}")
        import traceback
        traceback.print_exc()
