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 02: Congestion Resolution (Triple Crossing)...")

    # 1. Setup Environment (Open space)
    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. Define Netlist
    # Three nets that all converge on the same central area.
    # Negotiated Congestion must find non-overlapping paths for all of them.
    netlist = {
        "horizontal": (Port(10, 50, 0), Port(90, 50, 0)),
        "vertical_up": (Port(45, 10, 90), Port(45, 90, 90)),
        "vertical_down": (Port(55, 90, 270), Port(55, 10, 270)),
    }
    net_widths = dict.fromkeys(netlist, 2.0)

    # 3. Route with Negotiated Congestion
    # We increase the base penalty to encourage faster divergence
    pf = PathFinder(router, evaluator, base_congestion_penalty=1000.0)
    results = pf.route_all(netlist, net_widths)

    # 4. Check Results
    all_valid = all(r.is_valid for r in results.values())
    if all_valid:
        print("Success! Congestion resolved for all nets.")
    else:
        print("Some nets failed or have collisions.")
        for nid, res in results.items():
            print(f"  {nid}: valid={res.is_valid}, collisions={res.collisions}")

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


if __name__ == "__main__":
    main()
