import numpy as np
import time
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, plot_danger_map, plot_expanded_nodes
from shapely.geometry import box

def main() -> None:
    print("Running Example 07: Fan-Out (10 Nets, 50um Radius, 5um Grid)...")

    # 1. Setup Environment
    bounds = (0, 0, 1000, 1000)
    engine = CollisionEngine(clearance=6.0)
    
    # Bottleneck at x=500, 200um gap
    obstacles = [
        box(450, 0, 550, 400),
        box(450, 600, 550, 1000),
    ]
    for obs in obstacles:
        engine.add_static_obstacle(obs)

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

    evaluator = CostEvaluator(engine, danger_map, greedy_h_weight=1.5, unit_length_cost=0.5, bend_penalty=100.0, sbend_penalty=200.0, congestion_penalty=100.0)

    router = AStarRouter(evaluator, node_limit=1000000, snap_size=5.0)
    pf = PathFinder(router, evaluator, max_iterations=10, base_congestion_penalty=100.0)

    # 2. Define Netlist
    netlist = {}
    num_nets = 10
    start_x = 50
    start_y_base = 500 - (num_nets * 10.0) / 2.0
    
    end_x = 950
    end_y_base = 100
    end_y_pitch = 800.0 / (num_nets - 1)

    for i in range(num_nets):
        sy = round((start_y_base + i * 10.0) / 5.0) * 5.0
        ey = round((end_y_base + i * end_y_pitch) / 5.0) * 5.0
        netlist[f"net_{i:02d}"] = (Port(start_x, sy, 0), Port(end_x, ey, 0))

    net_widths = {nid: 2.0 for nid in netlist}

    def iteration_callback(idx, current_results):
        print(f"  Iteration {idx} finished. Successes: {sum(1 for r in current_results.values() if r.is_valid)}/{len(netlist)}")
        print(pf.router.get_metrics_summary())
        pf.router.reset_metrics()
        # fig, ax = plot_routing_results(current_results, obstacles, bounds, netlist=netlist)
        # plot_danger_map(danger_map, ax=ax)
        # fig.savefig(f"examples/07_iteration_{idx:02d}.png")
        # import matplotlib.pyplot as plt
        # plt.close(fig)

    # 3. Route
    print(f"Routing {len(netlist)} nets through 200um bottleneck...")
    import cProfile, pstats
    profiler = cProfile.Profile()
    profiler.enable()
    t0 = time.perf_counter()
    results = pf.route_all(netlist, net_widths, store_expanded=True, iteration_callback=iteration_callback)
    t1 = time.perf_counter()
    profiler.disable()
    stats = pstats.Stats(profiler).sort_stats('tottime')
    stats.print_stats(20)
    print(f"Routing took {t1-t0:.4f}s")

    # 4. Check Results
    success_count = sum(1 for res in results.values() if res.is_valid)
    print(f"Routed {success_count}/{len(netlist)} nets successfully.")
    
    for nid, res in results.items():
        if not res.is_valid:
            print(f"  FAILED: {nid}")
        else:
            types = [move.move_type for move in res.path]
            from collections import Counter
            counts = Counter(types)
            print(f"  {nid}: {len(res.path)} segments, {dict(counts)}")

    # 5. Visualize
    fig, ax = plot_routing_results(results, obstacles, bounds, netlist=netlist)
    
    # Overlay Danger Map
    plot_danger_map(danger_map, ax=ax)
    
    # Overlay Expanded Nodes from last routed net (as an example)
    if pf.router.last_expanded_nodes:
        print(f"Plotting {len(pf.router.last_expanded_nodes)} expanded nodes for the last net...")
        plot_expanded_nodes(pf.router.last_expanded_nodes, ax=ax, color='blue', alpha=0.1)

    fig.savefig("examples/07_large_scale_routing.png")
    print("Saved plot to examples/07_large_scale_routing.png")

if __name__ == "__main__":
    main()
