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

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

if (!values.dataDir || !values.workingDir) {
    console.error("--workingDir --dataDir");
    process.exit(1);
}

const workingDir = values.workingDir ?? '';
if (!fs.existsSync(workingDir)) mkdirSync(workingDir)
const dataDir = values.dataDir ?? '';

const tjaDir = path.join(dataDir, 'tja');
const files = fs.readdirSync(tjaDir);

const features: ({ songno: string, difficulty: 'oni' | 'ura' } & {})[] = [];
for (const file of files) {
    const tja = fs.readFileSync(path.join(tjaDir, file), 'utf-8');
    const songno = path.basename(file, '.tja');
    try {
        const parsed = parseTja(tja);
        const oni = parsed?.oni;
        const edit = parsed?.edit;
        if (oni) {
            features.push({
                songno,
                difficulty: 'oni',
                ...featurize(oni)
            })
        }
        if (edit) {
            features.push({
                songno,
                difficulty: 'ura',
                ...featurize(edit)
            })
        }
    }
    catch (err) {
        console.error(err);
        console.error(file);
    }
}

const featurePath = path.join(workingDir, values.fileName ?? 'features.json');
fs.writeFileSync(featurePath, JSON.stringify(features, null, 2), 'utf-8');