import Bun from 'bun';
import path from 'node:path';
import { parseArgs } from 'node:util';
import fs from 'node:fs';
import { factorize } from '../preprocess/factorize';
import { parseTja } from '../preprocess/parse';

const { values } = parseArgs({
    args: Bun.argv,
    options: {
        tja: { type: "string" },
        workingDir: { type: "string" },
        script: { type: "string" }
    },
    allowPositionals: true,
});

if (!values.tja || !values.workingDir || !values.script) {
    console.error("Usage: bun script/predict_tja_factor.ts --tja <path_to_tja> --workingDir <dir> --script <python_script>");
    process.exit(1);
}

const tjaPath = values.tja;
const workingDir = values.workingDir!;
const pythonScript = values.script!;

const tjaContent = fs.readFileSync(tjaPath, 'utf-8');
const songno = path.basename(tjaPath, '.tja');
const parsed = parseTja(tjaContent);

const factors: any[] = [];
if (parsed.oni) {
    factors.push({
        songno,
        difficulty: 'oni',
        factors: factorize(parsed.oni)
    });
}
if (parsed.edit) {
    factors.push({
        songno,
        difficulty: 'ura',
        factors: factorize(parsed.edit)
    });
}

if (factors.length === 0) {
    console.error("No Oni or Ura difficulty found.");
    process.exit(1);
}

const tempFactorPath = path.join(workingDir, `temp_predict_fact_${Date.now()}.json`);
fs.writeFileSync(tempFactorPath, JSON.stringify(factors, null, 2), 'utf-8');

try {
    const proc = Bun.spawnSync([
        "python3",
        pythonScript,
        "--workingDir", workingDir,
        "--feature", tempFactorPath, // 파이썬 스크립트 인자명이 --feature로 고정되어 있다고 가정
        "--songno", songno
    ]);

    if (proc.success) console.log(proc.stdout.toString());
    else console.error("Prediction failed:", proc.stderr.toString());
} finally {
    if (fs.existsSync(tempFactorPath)) fs.unlinkSync(tempFactorPath);
}
