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 03: Locked Paths...")

    # 1. Setup Environment
    bounds = (0, 0, 100, 100)
    engine = CollisionEngine(clearance=2.0)
    danger_map = DangerMap(bounds=bounds)
    danger_map.precompute([])

    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. Add a 'Pre-routed' net and lock it
    # Net 'fixed' goes right through the middle
    fixed_start = Port(10, 50, 0)
    fixed_target = Port(90, 50, 0)
    
    print("Routing initial net...")
    res_fixed = router.route(fixed_start, fixed_target, net_width=2.0)
    
    if res_fixed:
        # 3. Lock this net! It now behaves like a static obstacle
        geoms = [comp.geometry[0] for comp in res_fixed]
        engine.add_path("locked_net", geoms)
        engine.lock_net("locked_net")
        print("Initial net locked as static obstacle.")
    
    # Update danger map to reflect the new static obstacle
    danger_map.precompute(list(engine.static_geometries.values()))

    # 4. Route a new net that must detour around the locked one
    netlist = {
        "detour_net": (Port(50, 10, 90), Port(50, 90, 90)),
    }
    net_widths = {"detour_net": 2.0}

    print("Routing detour net around locked path...")
    results = pf.route_all(netlist, net_widths)

    # 5. Visualize
    # Add the locked net back to results for display
    from inire.router.pathfinder import RoutingResult
    display_results = {**results, "locked_net": RoutingResult("locked_net", res_fixed or [], True, 0)}
    
    fig, ax = plot_routing_results(display_results, list(engine.static_geometries.values()), bounds, netlist=netlist)
    fig.savefig("examples/03_locked_paths.png")
    print("Saved plot to examples/03_locked_paths.png")


if __name__ == "__main__":
    main()
