import { AtpAgent } from "@atproto/api";
import { readFileSync, readdirSync, statSync } from "fs";
import { join, dirname } from "path";
import { fileURLToPath } from "url";

const __dirname = dirname(fileURLToPath(import.meta.url));
const COLLECTION = "site.standard.document";
const CONTENT_DIR = join(__dirname, "../content");

function extractKeepRkeys(dir: string): Set<string> {
    const rkeys = new Set<string>();

    for (const entry of readdirSync(dir)) {
        const fullPath = join(dir, entry);
        if (statSync(fullPath).isDirectory()) {
            for (const rkey of extractKeepRkeys(fullPath)) {
                rkeys.add(rkey);
            }
        } else if (entry.endsWith(".mdx") || entry.endsWith(".md")) {
            const content = readFileSync(fullPath, "utf-8");
            const match = content.match(
                /atUri:\s*["']at:\/\/[^/]+\/site\.standard\.document\/([^"'\s]+)["']/
            );
            if (match) rkeys.add(match[1]);
        }
    }

    return rkeys;
}

async function main() {
    const handle = process.env.ATP_IDENTIFIER;
    const password = process.env.ATP_APP_PASSWORD;

    if (!handle || !password) {
        console.error("ATP_IDENTIFIER and ATP_APP_PASSWORD must be set.");
        process.exit(1);
    }

    const keepRkeys = extractKeepRkeys(CONTENT_DIR);
    console.log(`Found ${keepRkeys.size} records to keep from frontmatter`);

    const agent = new AtpAgent({ service: "https://bsky.social" });
    await agent.login({ identifier: handle, password });

    const did = agent.session!.did;
    console.log(`Logged in as ${did}`);

    // List all records
    const duplicates: { rkey: string; title: string }[] = [];
    let cursor: string | undefined;

    do {
        const res = await agent.com.atproto.repo.listRecords({
            repo: did,
            collection: COLLECTION,
            limit: 100,
            cursor,
        });

        for (const record of res.data.records) {
            const rkey = record.uri.split("/").pop()!;
            if (!keepRkeys.has(rkey)) {
                const value = record.value as Record<string, unknown>;
                duplicates.push({ rkey, title: (value.title as string) || "(untitled)" });
            }
        }

        cursor = res.data.cursor;
    } while (cursor);

    if (duplicates.length === 0) {
        console.log("No duplicates found — PDS is clean.");
        return;
    }

    console.log(`Removing ${duplicates.length} duplicate(s)...`);

    for (const dup of duplicates) {
        await agent.com.atproto.repo.deleteRecord({
            repo: did,
            collection: COLLECTION,
            rkey: dup.rkey,
        });
        console.log(`  ✅ Deleted: ${dup.title} (${dup.rkey})`);
    }

    console.log(`Removed ${duplicates.length} duplicate(s).`);
}

main().catch((err) => {
    console.error("Error:", err);
    process.exit(1);
});
