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
from shapely.geometry import box

def main() -> None:
    print("Running Example 09: Best-Effort (Unroutable Net)...")

    # 1. Setup Environment
    bounds = (0, 0, 100, 100)
    engine = CollisionEngine(clearance=2.0)
    
    # Create a 'cage' that completely blocks the target
    cage = [
        box(70, 30, 75, 70), # Left wall
        box(70, 70, 95, 75), # Top wall
        box(70, 25, 95, 30), # Bottom wall
    ]
    for obs in cage:
        engine.add_static_obstacle(obs)

    danger_map = DangerMap(bounds=bounds)
    danger_map.precompute(cage)

    evaluator = CostEvaluator(engine, danger_map, bend_penalty=50.0, sbend_penalty=150.0)
    # Use a low node limit to fail faster
    router = AStarRouter(evaluator, node_limit=2000, snap_size=1.0, straight_lengths=[1.0, 5.0, 25.0], bend_radii=[10.0])
    
    # Enable partial path return
    pf = PathFinder(router, evaluator)

    # 2. Define Netlist: start outside, target inside the cage
    netlist = {
        "trapped_net": (Port(10, 50, 0), Port(85, 50, 0)),
    }
    net_widths = {"trapped_net": 2.0}

    # 3. Route
    print("Routing net into a cage (should fail and return partial)...")
    results = pf.route_all(netlist, net_widths)

    # 4. Check Results
    res = results["trapped_net"]
    if not res.is_valid:
        print(f"Net failed to route as expected. Partial path length: {len(res.path)} segments.")
    else:
        print("Wait, it found a way in? Check the cage geometry!")

    # 5. Visualize
    fig, ax = plot_routing_results(results, cage, bounds, netlist=netlist)
    fig.savefig("examples/09_unroutable_best_effort.png")
    print("Saved plot to examples/09_unroutable_best_effort.png")

if __name__ == "__main__":
    main()
