"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getWordList = void 0;
const types_1 = require("@scrabble-solver/types");
const cheerio_1 = require("cheerio");
const fs_1 = __importDefault(require("fs"));
const url_1 = require("url");
const lib_1 = require("../lib");
const PAGE_URL = 'https://sjp.pl/sl/growy/';
const FILE_TO_EXTRACT_FROM_ZIP = 'slowa.txt';
const REASONABLE_VALID_WORD_COUNT_TRESHOLD = 2_000_000; // more like 3M, but just to be safe
const SECONDARY_FILE_URL = 'https://raw.githubusercontent.com/kamilmielnik/scrabble-dictionaries/refs/heads/master/polish/sjp.txt';
const getWordList = async () => {
    try {
        const tempFilepath = (0, lib_1.getTempFilepath)();
        const zipUrl = await fetchZipUrl(PAGE_URL);
        const zipTempFilename = await (0, lib_1.downloadFile)(zipUrl);
        await (0, lib_1.unzip)(zipTempFilename, FILE_TO_EXTRACT_FROM_ZIP, tempFilepath);
        fs_1.default.unlinkSync(zipTempFilename);
        const file = fs_1.default.readFileSync(tempFilepath, 'utf-8');
        fs_1.default.unlinkSync(tempFilepath);
        const words = (0, lib_1.extractWords)(file.toLocaleString(), 'pl-PL');
        if (words.length < REASONABLE_VALID_WORD_COUNT_TRESHOLD) {
            return getBackupWordList();
        }
        return words;
    }
    catch {
        return getBackupWordList();
    }
};
exports.getWordList = getWordList;
const fetchZipUrl = async (url) => {
    const html = await (0, lib_1.downloadHtml)(url);
    const filename = parseZipContainingPage(html);
    const { href } = new url_1.URL(filename, url);
    return href;
};
const parseZipContainingPage = (html) => {
    const $ = (0, cheerio_1.load)(html);
    const $links = $('a');
    const links = Array.from($links)
        .map((link) => $(link).attr('href'))
        .filter(Boolean);
    const zipFilename = links.find((link) => link.endsWith('.zip'));
    if (typeof zipFilename === 'undefined') {
        throw new Error('Cannot find link to zip file on the page');
    }
    return zipFilename;
};
const getBackupWordList = () => {
    return (0, lib_1.getTxtWordList)(SECONDARY_FILE_URL, types_1.Locale.PL_PL);
};
