"""Write a submission CSV that passes validate_submission.py. Contract enforced here: * header exactly: candidate_id,rank,score,reasoning * exactly top_n (default 100) rows * rank 1..N unique, score non-increasing by rank * ties broken by candidate_id ascending * UTF-8, quoted reasoning field Note on sample dataset ---------------------- The provided sample_candidates.json contains only 50 profiles. The challenge validator requires exactly 100 rows. When running against the full test dataset (which contains 5,000+ profiles), top_n=100 will always be satisfied. For sample-only runs, pass ``top_n=len(candidates)`` or use ``--top 50``. """ from __future__ import annotations import csv from typing import List from .scoring import ScoredCandidate HEADER = ["candidate_id", "rank", "score", "reasoning"] def rank_and_write( scored: List[ScoredCandidate], out_path: str, top_n: int = 100, ) -> None: """Sort, clip to top_n, enforce non-increasing scores, and write CSV. If the pool is smaller than top_n, writes all available candidates (the validator will flag this for the sample dataset — expected behaviour). """ if not scored: raise ValueError("No scored candidates provided.") # Sort by score desc, then candidate_id asc for deterministic tie-breaks. ordered = sorted(scored, key=lambda c: (-c.score, c.candidate_id)) top = ordered[:top_n] # Enforce non-increasing scores even after rounding to 4 decimals. rounded: List[float] = [round(c.score, 4) for c in top] for i in range(1, len(rounded)): if rounded[i] > rounded[i - 1]: rounded[i] = rounded[i - 1] with open(out_path, "w", encoding="utf-8", newline="") as f: writer = csv.writer(f, quoting=csv.QUOTE_MINIMAL) writer.writerow(HEADER) for rank, (c, sc) in enumerate(zip(top, rounded), start=1): writer.writerow([c.candidate_id, rank, f"{sc:.4f}", c.reasoning]) # Print a quick summary to console. n_written = len(top) print(f"\nTop-5 candidates:") for i, (c, sc) in enumerate(zip(top[:5], rounded[:5]), 1): print(f" #{i} {c.candidate_id} score={sc:.4f} {c.reasoning[:80]}…") if n_written < top_n: print( f"\n⚠️ Only {n_written} candidates available (pool smaller than top_n={top_n})." f"\n Run against the full dataset to produce a valid 100-row submission." )