#!/usr/bin/env python3
"""
KiCad Schematic API - Demo File Generator

Generates an interactive demo Python file showcasing kicad-sch-api features.

Usage:
    ksa_demo
    ksa_demo --force
"""

import argparse
import sys
from pathlib import Path
from typing import Optional

DEMO_TEMPLATE = '''#!/usr/bin/env python3
"""
kicad-sch-api Interactive Demo
Generated by: ksa_demo

This demo shows library features for programmatic circuit generation.
Each section demonstrates a different capability.

Requirements:
    pip install kicad-sch-api

Usage:
    python ksa_demo.py
"""

import kicad_sch_api as ksa
from pathlib import Path

print("Starting kicad-sch-api demo...")
print("This demo creates 4 example schematics demonstrating key features.")
print()

# ============================================================
# DEMO 1: Create Basic Circuit (Resistor Divider)
# ============================================================
print("=" * 60)
print("DEMO 1: Creating a basic resistor divider circuit")
print("=" * 60)

try:
    # Create a new schematic
    sch = ksa.create_schematic("Demo1_BasicDivider")

    # Add power symbols
    sch.components.add(
        lib_id="power:GND",
        reference="#PWR01",
        value="GND",
        position=(100.0, 120.0),
    )

    sch.components.add(
        lib_id="power:+5V",
        reference="#PWR02",
        value="+5V",
        position=(100.0, 60.0),
    )

    # Add resistors
    r1 = sch.components.add(
        lib_id="Device:R",
        reference="R1",
        value="10k",
        position=(100.0, 75.0),
    )

    r2 = sch.components.add(
        lib_id="Device:R",
        reference="R2",
        value="10k",
        position=(100.0, 105.0),
    )

    # Connect the circuit
    sch.add_wire(start=(100.0, 60.0), end=(100.0, 70.0))   # +5V to R1
    sch.add_wire(start=(100.0, 80.0), end=(100.0, 90.0))   # R1 to output
    sch.add_wire(start=(100.0, 100.0), end=(100.0, 110.0)) # R2 to output
    sch.add_wire(start=(100.0, 90.0), end=(110.0, 90.0))   # Output tap

    # Add junction and output label
    sch.junctions.add(position=(100.0, 90.0))
    sch.add_label(text="VOUT", position=(110.0, 90.0))

    # Save the schematic
    output_file = Path("demo_1_divider.kicad_sch")
    sch.save(output_file)

    print(f"✅ Created basic resistor divider: {output_file}")
    print(f"   Components: 2 resistors, 2 power symbols")
    print(f"   Output: Voltage divider with VOUT label")
    print()

except Exception as e:
    print(f"❌ Error in Demo 1: {e}")
    print(f"   This may indicate missing KiCad symbol libraries")
    print()


# ============================================================
# DEMO 2: Parametric Layout with Circuit Arrays
# ============================================================
print("=" * 60)
print("DEMO 2: Creating an array of 10 voltage dividers")
print("=" * 60)

try:
    # Create new schematic
    sch = ksa.create_schematic("Demo2_CircuitArray")

    # Parameters for array layout
    num_dividers = 10
    spacing_x = 50.0  # Spacing between dividers in mm
    start_x = 50.0
    start_y = 80.0

    print(f"Creating {num_dividers} voltage dividers in a row...")

    for i in range(num_dividers):
        # Calculate position for this divider
        x = start_x + (i * spacing_x)
        y = start_y

        # Add components for this divider
        sch.components.add(
            lib_id="power:GND",
            reference=f"#PWR0{10+i}",
            value="GND",
            position=(x, y + 40.0),
        )

        sch.components.add(
            lib_id="power:+5V",
            reference=f"#PWR0{i}",
            value="+5V",
            position=(x, y - 20.0),
        )

        sch.components.add(
            lib_id="Device:R",
            reference=f"R{i*2+1}",
            value="10k",
            position=(x, y - 5.0),
        )

        sch.components.add(
            lib_id="Device:R",
            reference=f"R{i*2+2}",
            value="10k",
            position=(x, y + 25.0),
        )

        # Wire up this divider
        sch.add_wire(start=(x, y - 20.0), end=(x, y - 10.0))  # +5V to R1
        sch.add_wire(start=(x, y), end=(x, y + 10.0))         # R1 to output
        sch.add_wire(start=(x, y + 20.0), end=(x, y + 30.0))  # R2 to output
        sch.add_wire(start=(x, y + 10.0), end=(x, y + 20.0))  # Output connection
        sch.add_wire(start=(x, y + 30.0), end=(x, y + 40.0))  # Output to GND

        # Add junction and label for this output
        sch.junctions.add(position=(x, y + 15.0))
        sch.add_label(text=f"OUT{i}", position=(x + 5.0, y + 15.0))

    output_file = Path("demo_2_array.kicad_sch")
    sch.save(output_file)

    print(f"✅ Created array of {num_dividers} voltage dividers: {output_file}")
    print(f"   Total components: {num_dividers * 4} (40 components)")
    print(f"   Layout: Horizontal array with {spacing_x}mm spacing")
    print(f"   Demonstrates programmatic circuit generation")
    print()

except Exception as e:
    print(f"❌ Error in Demo 2: {e}")
    print()


# ============================================================
# DEMO 3: Bulk Operations on Components
# ============================================================
print("=" * 60)
print("DEMO 3: Bulk operations - changing all resistor values")
print("=" * 60)

try:
    # Load the array we just created
    sch = ksa.load_schematic("demo_2_array.kicad_sch")

    print("Updating all resistors from 10k to 4.7k...")

    # Get all components
    component_count = 0
    updated_count = 0

    for component in sch.components:
        component_count += 1
        # Check if this is a resistor
        if component.reference.startswith("R"):
            # Update the value
            component.value = "4.7k"
            updated_count += 1

    # Save the modified schematic
    output_file = Path("demo_3_bulk_update.kicad_sch")
    sch.save(output_file)

    print(f"✅ Bulk update complete: {output_file}")
    print(f"   Scanned {component_count} components")
    print(f"   Updated {updated_count} resistors")
    print(f"   Demonstrates component iteration and modification")
    print()

except Exception as e:
    print(f"❌ Error in Demo 3: {e}")
    print()


# ============================================================
# DEMO 4: Format Preservation - Exact KiCad Compatibility
# ============================================================
print("=" * 60)
print("DEMO 4: Round-trip format preservation")
print("=" * 60)

try:
    # Load an existing file
    input_file = Path("demo_3_bulk_update.kicad_sch")
    sch = ksa.load_schematic(input_file)

    # Make a small change
    sch.add_text(
        text="Modified with kicad-sch-api",
        position=(50.0, 150.0),
        size=2.0,
    )

    # Save it back
    output_file = Path("demo_4_roundtrip.kicad_sch")
    sch.save(output_file)

    print(f"✅ Round-trip save complete: {output_file}")
    print(f"   Added text annotation")
    print(f"   All original properties preserved")
    print(f"   File opens in KiCad without issues")
    print()

except Exception as e:
    print(f"❌ Error in Demo 4: {e}")
    print()


# ============================================================
# Summary
# ============================================================
print("=" * 60)
print("DEMO COMPLETE!")
print("=" * 60)
print()
print("Generated files:")
print("  1. demo_1_divider.kicad_sch       - Basic resistor divider")
print("  2. demo_2_array.kicad_sch         - Array of 10 dividers")
print("  3. demo_3_bulk_update.kicad_sch   - Bulk value update")
print("  4. demo_4_roundtrip.kicad_sch     - Round-trip preservation")
print()
print("Open these files in KiCad 8 to see the results")
print()
print("Key takeaways:")
print("  - Programmatic circuit creation with Python")
print("  - Bulk component operations")
print("  - Exact format preservation")
print("  - Parametric layout generation")
print()
print("Next steps:")
print("  - Read the docs: https://github.com/circuit-synth/kicad-sch-api")
print("  - Install Claude Code commands: ksa-claude-setup")
print("  - Build circuits programmatically")
print()
'''


def main(argv: Optional[list] = None) -> int:
    """
    Main CLI entry point for ksa_demo.

    Args:
        argv: Command-line arguments (None = sys.argv)

    Returns:
        Exit code (0 = success, 1 = error)
    """
    parser = argparse.ArgumentParser(
        prog="ksa_demo",
        description="Generate interactive demo file showcasing kicad-sch-api features",
        epilog="Creates ksa_demo.py in the current directory",
    )

    parser.add_argument(
        "--force",
        "-f",
        action="store_true",
        help="Overwrite existing ksa_demo.py if it exists",
    )

    args = parser.parse_args(argv)

    try:
        # Target file in current directory
        output_file = Path.cwd() / "ksa_demo.py"

        # Check if file exists
        if output_file.exists() and not args.force:
            print(
                f"❌ Error: {output_file} already exists. " f"Use --force to overwrite.",
                file=sys.stderr,
            )
            return 1

        # Write the demo file
        output_file.write_text(DEMO_TEMPLATE)

        # Make it executable on Unix-like systems
        try:
            import stat

            current_permissions = output_file.stat().st_mode
            output_file.chmod(current_permissions | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
        except Exception:
            # Ignore chmod errors on Windows
            pass

        # Success message
        print(f"✅ Created {output_file}")
        print(f"Run with: python ksa_demo.py")
        print(f"Demo showcases: circuit generation, arrays, bulk operations, format preservation")
        print()
        print(f"The demo will create 4 example KiCad schematics:")
        print(f"  1. Basic circuit creation")
        print(f"  2. Parametric array generation (10 circuits)")
        print(f"  3. Bulk component updates")
        print(f"  4. Round-trip format preservation")

        return 0

    except PermissionError as e:
        print(f"❌ Permission error: {e}", file=sys.stderr)
        return 1

    except Exception as e:
        print(f"❌ Unexpected error: {e}", file=sys.stderr)
        import traceback

        traceback.print_exc()
        return 1


def entry_point() -> None:
    """Entry point for setuptools console_scripts."""
    sys.exit(main())


if __name__ == "__main__":
    sys.exit(main())
