from shapely.geometry import Polygon

from inire.geometry.collision import CollisionEngine
from inire.geometry.primitives import Port
from inire.router.astar import AStarRouter
from inire.router.cost import CostEvaluator
from inire.router.danger_map import DangerMap
from inire.router.pathfinder import PathFinder
from inire.utils.visualization import plot_routing_results


def main() -> None:
    print("Running Example 01: Simple Route...")

    # 1. Setup Environment
    # Define the routing area bounds (minx, miny, maxx, maxy)
    bounds = (0, 0, 100, 100)

    engine = CollisionEngine(clearance=2.0)
    danger_map = DangerMap(bounds=bounds)

    # Add a simple rectangular obstacle
    obstacle = Polygon([(30, 20), (70, 20), (70, 40), (30, 40)])
    engine.add_static_obstacle(obstacle)

    # Precompute the danger map (distance field) for heuristics
    danger_map.precompute([obstacle])

    evaluator = CostEvaluator(engine, danger_map, bend_penalty=50.0, sbend_penalty=150.0)
    router = AStarRouter(evaluator, snap_size=1.0, straight_lengths=[1.0, 5.0, 25.0], bend_radii=[10.0])
    pf = PathFinder(router, evaluator)

    # 2. Define Netlist
    # Route from (10, 10) to (90, 50)
    # The obstacle at y=20-40 blocks the direct path.
    netlist = {
        "simple_net": (Port(10, 10, 0), Port(90, 50, 0)),
    }
    net_widths = {"simple_net": 2.0}

    # 3. Route
    results = pf.route_all(netlist, net_widths)

    # 4. Check Results
    if results["simple_net"].is_valid:
        print("Success! Route found.")
        print(f"Path collisions: {results['simple_net'].collisions}")
    else:
        print("Failed to route.")

    # 5. Visualize
    fig, ax = plot_routing_results(results, [obstacle], bounds, netlist=netlist)
    fig.savefig("examples/01_simple_route.png")
    print("Saved plot to examples/01_simple_route.png")


if __name__ == "__main__":
    main()
