import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/**
 * @copyright Sister Software
 * @license AGPL-3.0
 * @author Teffen Ellis, et al.
 */
import { ProgressBar } from "@inkjs/ui";
import { Box, Text } from "ink";
import { formatQuantity, Placetype, PLACETYPES_REPO_SOURCE, synchronizeRepo, takeInParallel, } from "mailwoman/core";
import { availableParallelism } from "node:os";
import { PathBuilder } from "path-ts";
import { useEffect, useMemo, useState } from "react";
import zod from "zod";
import { $ } from "zx";
const BATCH_SIZE = availableParallelism();
const WOF_REPO_OWNER = "whosonfirst-data";
const ArgumentsSchema = zod.array(zod.string().describe("Path to the Who's On First repository admin directory"));
export { ArgumentsSchema as args };
const WOFSync = ({ args }) => {
    const [repos, setRepos] = useState();
    const localRepoDirectory = useMemo(() => PathBuilder.from(args[0]), [args]);
    const [syncCount, setSyncCount] = useState(0);
    const percentage = Array.isArray(repos) ? (syncCount / repos.length) * 100 : 0;
    useEffect(() => {
        const result = $.sync `gh repo list ${WOF_REPO_OWNER} --no-archived --json 'name' --json 'url'`
            .json()
            .map((entry) => ({ ...entry, owner: WOF_REPO_OWNER }));
        setRepos([...result, PLACETYPES_REPO_SOURCE]);
    }, [localRepoDirectory]);
    useEffect(() => {
        if (!repos || !repos.length)
            return;
        const abortController = new AbortController();
        const batchIterator = takeInParallel(repos, BATCH_SIZE, async (entry) => {
            await synchronizeRepo(entry, localRepoDirectory);
            setSyncCount((count) => count + 1);
        }, abortController.signal);
        Array.fromAsync(batchIterator);
        return () => {
            abortController.abort();
        };
    }, [repos, localRepoDirectory]);
    useEffect(() => {
        if (!repos)
            return;
        if (syncCount < repos.length)
            return;
        Placetype.prepare({
            batchSize: BATCH_SIZE,
            localRepoDirectory,
        });
    }, [localRepoDirectory, repos, syncCount]);
    if (!repos) {
        return _jsx(Text, { children: "Fetching repo list..." });
    }
    if (!repos.length) {
        return _jsx(Text, { children: "No repositories found" });
    }
    return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Box, { children: [_jsxs(Text, { children: ["Inserted ", formatQuantity(syncCount)] }), _jsxs(Text, { children: ["\u00A0of\u00A0", formatQuantity(repos.length)] }), _jsx(Text, { children: "\u00A0records" })] }), _jsxs(Box, { paddingX: 1, children: [_jsx(ProgressBar, { value: percentage }), _jsxs(Text, { children: [percentage.toFixed(2), "%"] })] })] }));
};
export default WOFSync;
//# sourceMappingURL=sync.js.map