import Bun from 'bun';
import path from 'node:path';
import { parseArgs } from 'node:util';
import fs, { mkdirSync } from 'node:fs';
import { factorize } from '../preprocess/factorize';
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 --fileName");
    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 results: any[] = [];
for (const file of files) {
    if (!file.endsWith('.tja')) continue;
    const tja = fs.readFileSync(path.join(tjaDir, file), 'utf-8');
    const songno = path.basename(file, '.tja');
    try {
        const parsed = parseTja(tja);
        const courses = [
            { diff: 'oni', data: parsed?.oni },
            { diff: 'ura', data: parsed?.edit }
        ];

        for (const course of courses) {
            if (course.data) {
                results.push({
                    songno,
                    difficulty: course.diff,
                    factors: factorize(course.data)
                });
            }
        }
    }
    catch (err) {
        console.error(`[Error] ${file}:`, err);
    }
}

const outputPath = path.join(workingDir, values.fileName ?? 'factors.json');
fs.writeFileSync(outputPath, JSON.stringify(results, null, 2), 'utf-8');
console.log(`Successfully saved factors to ${outputPath}`);
