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 04: S-Bends and Multiple Radii...")

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

    # 2. Configure Router
    evaluator = CostEvaluator(
        engine,
        danger_map,
        unit_length_cost=1.0,
        greedy_h_weight=1.5,
        bend_penalty=10.0,
        sbend_penalty=20.0,
    )

    router = AStarRouter(
        evaluator,
        node_limit=50000,
        snap_size=1.0,
        bend_radii=[10.0, 30.0],
        sbend_offsets=[5.0], # Use a simpler offset
        sbend_radii=[10.0],
        bend_penalty=10.0,
        sbend_penalty=20.0,
        snap_to_target_dist=50.0, # Large snap range
    )

    pf = PathFinder(router, evaluator)

    # 3. Define Netlist
    # start (10, 50), target (60, 55) -> 5um offset
    netlist = {
        "sbend_only": (Port(10, 50, 0), Port(60, 55, 0)),
        "multi_radii": (Port(10, 10, 0), Port(90, 90, 0)),
    }
    net_widths = {"sbend_only": 2.0, "multi_radii": 2.0}

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

    # 5. Check Results
    for nid, res in results.items():
        status = "Success" if res.is_valid else "Failed"
        print(f"{nid}: {status}, collisions={res.collisions}")

    # 6. Visualize
    fig, ax = plot_routing_results(results, [], bounds, netlist=netlist)
    fig.savefig("examples/04_sbends_and_radii.png")
    print("Saved plot to examples/04_sbends_and_radii.png")


if __name__ == "__main__":
    main()
