import Bun from 'bun';
import path from 'node:path';
import { parseArgs } from 'node:util';
import fs from 'node:fs';
import { featurize } from '../preprocess/featurize';
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_feature.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 features: any[] = [];
if (parsed.oni) features.push({ songno, difficulty: 'oni', ...featurize(parsed.oni) });
if (parsed.edit) features.push({ songno, difficulty: 'ura', ...featurize(parsed.edit) });

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

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

try {
    const proc = Bun.spawnSync(["python3", pythonScript, "--workingDir", workingDir, "--feature", tempFeaturePath, "--songno", songno]);
    if (proc.success) console.log(proc.stdout.toString());
    else console.error("Prediction failed:", proc.stderr.toString());
} finally {
    if (fs.existsSync(tempFeaturePath)) fs.unlinkSync(tempFeaturePath);
}
