import { assert } from "../../../../assert.js";
import { compute_kway_params } from "./compute_kway_params.js";

/**
 * Project the partition assignment from `graph.coarser_graph` down to `graph`,
 * then compute the k-way refinement bookkeeping at the fine level.
 *
 * Each fine vertex inherits the partition of its coarse parent
 * (`coarse_vertex_map[v]` maps fine→coarse). After projection,
 * `vertex_partition`, `partition_weights`, the `internal_degree` /
 * `external_degree` / `neighbor_partition_*` arrays, the boundary list, and
 * `current_cut` are all rebuilt from scratch.
 *
 * METIS's `ProjectKWayPartition` folds the projection into the parameter-compute
 * pass and uses the coarse graph's `external_degree[]` as a hint to skip vertices
 * that are guaranteed interior. That's a measurable speedup at scale, but the
 * state coupling isn't worth it in v1 — we just project then call the standard
 * compute routine.
 *
 * @param {import('../MetisGraph.js').MetisGraph} graph the fine graph (must have
 *   `.coarser_graph` set and that coarser graph's `vertex_partition` populated)
 * @param {number} partition_count
 */
export function project_kway(graph, partition_count) {
    const coarser_graph = graph.coarser_graph;
    const coarse_vertex_map = graph.coarse_vertex_map;

    assert.equal(coarser_graph !== null, true, 'graph.coarser_graph must be set before projection');
    assert.equal(coarse_vertex_map !== null, true, 'graph.coarse_vertex_map must be set before projection');
    assert.equal(coarser_graph.vertex_partition !== null, true, 'coarser_graph.vertex_partition must be populated before projection');

    graph.allocate_partition_state(partition_count);

    const fine_partition = graph.vertex_partition;
    const coarse_partition = coarser_graph.vertex_partition;
    const vertex_count = graph.vertex_count;

    for (let vertex = 0; vertex < vertex_count; vertex++) {
        fine_partition[vertex] = coarse_partition[coarse_vertex_map[vertex]];
    }

    compute_kway_params(graph, partition_count);
}
