#!/usr/bin/env python3 """Build a deterministic sampled course list for publishing. Sources: 1. Blast columns that match *_exp from temporary/all_email_blasts_consolidated.csv. 2. Certification names from raw_data/expirations.csv (column: certification). All discovered course names are deduplicated, ordered by salted hash, and written to: temporary/sampled_courses.csv """ from __future__ import annotations import argparse import csv import hashlib from pathlib import Path def parse_args() -> argparse.Namespace: project_root = Path(__file__).resolve().parent.parent parser = argparse.ArgumentParser( description="Create deterministically ordered sampled course list." ) parser.add_argument( "--blast-file", default=str(project_root / "temporary" / "all_email_blasts_consolidated.csv"), help="Path to consolidated blast CSV.", ) parser.add_argument( "--expirations-file", default=str(project_root / "raw_data" / "expirations.csv"), help="Path to expirations CSV.", ) parser.add_argument( "--env-file", default=str(project_root / ".env"), help="Path to .env with SALT.", ) parser.add_argument( "--output", default=str(project_root / "temporary" / "sampled_courses.csv"), help="Output CSV path.", ) return parser.parse_args() def read_salt(env_path: Path) -> str: if not env_path.exists(): raise FileNotFoundError(f"Required env file not found: {env_path}") salt = "" with env_path.open("r", encoding="utf-8") as f: for line in f: stripped = line.strip() if not stripped or stripped.startswith("#"): continue if stripped.startswith("SALT="): salt = stripped.split("=", 1)[1].strip().strip('"').strip("'") break if not salt: raise RuntimeError(f"SALT was not found or empty in: {env_path}") return salt def derive_course_ordering_hash(salt: str) -> str: return hashlib.sha256(f"{salt}course".encode("utf-8")).hexdigest() def read_exp_columns_from_blast(blast_path: Path) -> set[str]: if not blast_path.exists(): raise FileNotFoundError(f"Required blast file not found: {blast_path}") with blast_path.open("r", encoding="utf-8", newline="") as f: reader = csv.DictReader(f) if not reader.fieldnames: raise RuntimeError(f"Blast file has no header: {blast_path}") course_names = { col.strip().lower().removesuffix("_exp") for col in reader.fieldnames if col and col.strip().lower().endswith("_exp") } return {c for c in course_names if c} def read_certifications(expirations_path: Path) -> set[str]: if not expirations_path.exists(): raise FileNotFoundError( f"Required expirations file not found: {expirations_path}" ) certifications: set[str] = set() with expirations_path.open("r", encoding="utf-8", newline="") as f: reader = csv.DictReader(f) if not reader.fieldnames: raise RuntimeError(f"Expirations file has no header: {expirations_path}") if "certification" not in reader.fieldnames: raise RuntimeError( "Expirations file missing required 'certification' column: " f"{expirations_path}" ) for row in reader: cert = (row.get("certification") or "").strip().lower() if cert: certifications.add(cert) return certifications def course_order_hash(course_ordering_hash: str, course_name: str) -> str: return hashlib.sha256(f"{course_ordering_hash}{course_name}".encode("utf-8")).hexdigest() def write_courses(output_path: Path, courses: list[str]) -> None: output_path.parent.mkdir(parents=True, exist_ok=True) with output_path.open("w", encoding="utf-8", newline="") as f: writer = csv.writer(f) writer.writerow(["course"]) for course in courses: writer.writerow([course]) def main() -> None: args = parse_args() blast_path = Path(args.blast_file) expirations_path = Path(args.expirations_file) env_path = Path(args.env_file) output_path = Path(args.output) salt = read_salt(env_path) course_ordering_hash = derive_course_ordering_hash(salt) blast_courses = read_exp_columns_from_blast(blast_path) expiration_courses = read_certifications(expirations_path) all_courses = blast_courses | expiration_courses if not all_courses: raise RuntimeError("No course values were found from either source.") ordered_courses = [ value for _, value in sorted( ( (course_order_hash(course_ordering_hash, value), value) for value in all_courses ), key=lambda pair: (pair[0], pair[1]), ) ] write_courses(output_path, ordered_courses) print(f"Blast *_exp courses: {len(blast_courses)}") print(f"Expiration certifications: {len(expiration_courses)}") print(f"Total unique courses written: {len(ordered_courses)}") print(f"Output: {output_path}") if __name__ == "__main__": main()