import { Card, DBReader } from "./src/dbreader";
import _ from "lodash";
import { PackDbFetcher } from "./src/packdbfetcher";
import { Banlist, mergeBanlists, readLFList } from "./src/utility";
import moment from "moment";
import fs from 'fs';

const DATE = process.env.DATE;
const lflistPath = process.env.LFLIST_PATH || "./lflist.conf";
const includes = (process.env.INCLUDES || "").split(",").filter(i => i).map(i => parseInt(i.trim()));
const excludes = new Set((process.env.EXCLUDES || "").split(",").filter(i => i).map(i => parseInt(i.trim())));

async function getBanlist() {
	const lflistData = await fs.promises.readFile(lflistPath, 'utf-8');
	const lflists = (await readLFList(lflistData)).filter(l => !l.name.includes('TCG')).map(l => ({
		...l,
		date: moment(l.name.split(' ')[0], 'YYYY.MM')
	})).filter(l => l.date.isBefore(DATE));
	const lflist = _.maxBy(lflists, l => l.date.unix());
	const extraLflistPath = `./extras/${process.env.FILE_SYMBOL}/lflist.conf`;
	let extraLflist: Banlist;
	try {
		const extraLflistContent = await fs.promises.readFile(extraLflistPath, 'utf-8');
		extraLflist = (await readLFList(extraLflistContent))[0];
	} catch (e) { }
	return (lflist && extraLflist) ? mergeBanlists([lflist, extraLflist]) : lflist || extraLflist;
}

async function main() {
	const dbreader = new DBReader({
		name: "Database",
		//level: Logger.DEBUG
	});
	await dbreader.init();
	const cards = (await PackDbFetcher.fetchOnce(dbreader, `date <= '${DATE}'`))
		.filter(c => !excludes.has(c.code));
	const existingIds = new Set(cards.map(c => c.code));
	for (const include of includes) { 
		if (!existingIds.has(include)) {
			cards.push(new Card(include));
		}
	}
	console.log(cards.length);
	
	const extraBanlist = await getBanlist();
	await dbreader.run(cards, {
		extraBanlists: extraBanlist ? [extraBanlist] : undefined,
	});
	process.exit();
}
main();
