// cli/src/score-loader.ts
// 加载"按省按年"的省考进面分/报名人数参考库 (cli/data/scores/<slug>-<year>.json.gz)。
// 进面分/报名为历史参考(各省年份/计分制不同)，登录门控省无逐岗数据。
import { readFileSync, existsSync } from "node:fs";
import { join, dirname } from "node:path";
import { gunzipSync } from "node:zlib";
import { fileURLToPath } from "node:url";
import { resolveProvince, PROVINCES } from "./codes.js";
const __dirname = dirname(fileURLToPath(import.meta.url));
const CANDIDATE_DIRS = [
    join(__dirname, "..", "data", "scores"),
    join(__dirname, "..", "..", "data", "scores"),
    join(__dirname, "..", "..", "cli", "data", "scores"),
];
function scoresDir() {
    for (const d of CANDIDATE_DIRS)
        if (existsSync(d))
            return d;
    return null;
}
/** 省份名/拼音/代码 → slug(拼音)。 */
export function provinceToSlug(input) {
    const id = resolveProvince(input);
    return id ? PROVINCES[id]?.pinyin ?? null : null;
}
let indexCache = null;
export function loadScoreIndex() {
    if (indexCache)
        return indexCache;
    const dir = scoresDir();
    if (!dir)
        return (indexCache = []);
    const p = join(dir, "index.json");
    if (!existsSync(p))
        return (indexCache = []);
    try {
        return (indexCache = JSON.parse(readFileSync(p, "utf-8")));
    }
    catch {
        return (indexCache = []);
    }
}
/** 加载某省某年的参考数据；year 省略时取该省最新可用年份。 */
export function loadScore(slug, year) {
    const dir = scoresDir();
    if (!dir)
        return null;
    let y = year;
    if (!y) {
        const years = loadScoreIndex().filter((e) => e.slug === slug).map((e) => e.year).sort((a, b) => b - a);
        if (!years.length)
            return null;
        y = years[0];
    }
    const p = join(dir, `${slug}-${y}.json.gz`);
    if (!existsSync(p))
        return null;
    try {
        return JSON.parse(gunzipSync(readFileSync(p)).toString("utf-8"));
    }
    catch {
        return null;
    }
}
export function scoreYears(slug) {
    return loadScoreIndex().filter((e) => e.slug === slug).map((e) => e.year).sort((a, b) => a - b);
}
/** 含某类数据(进面分/报名)的最新年份——进面分与报名常分属不同年份。 */
export function latestYearWith(slug, kind) {
    return loadScoreIndex()
        .filter((e) => e.slug === slug && e[kind] > 0)
        .map((e) => e.year)
        .sort((a, b) => b - a)[0];
}
/** 进面分统计(min/中位/max)。 */
export function cutoffStats(cutoffs) {
    if (!cutoffs.length)
        return null;
    const s = cutoffs.map((c) => c.cutoff).sort((a, b) => a - b);
    return { count: s.length, min: s[0], median: s[Math.floor(s.length / 2)], max: s[s.length - 1] };
}
