import { AtpAgent } from "@atproto/api";
import { writeFileSync, mkdirSync, existsSync } from "fs";
import { join, dirname } from "path";
import { fileURLToPath } from "url";

const STANDARD_DID = "did:plc:re3ebnp5v7ffagz6rb6xfei4";
const LEXICON_COLLECTION = "com.atproto.lexicon.schema";

const LEXICONS_TO_SYNC = [
  "site.standard.publication",
  "site.standard.document",
  "site.standard.theme.basic",
  "site.standard.theme.color",
  "site.standard.graph.subscription",
  "site.standard.graph.recommend",
  "site.standard.authFull",
  "site.standard.authSocial",
];

const __dirname = dirname(fileURLToPath(import.meta.url));
const OUTPUT_DIR = join(__dirname, "../app/data/lexicons");

const agent = new AtpAgent({
  service: "https://bsky.social",
});

async function fetchLexicon(nsid: string) {
  const response = await agent.com.atproto.repo.getRecord({
    repo: STANDARD_DID,
    collection: LEXICON_COLLECTION,
    rkey: nsid,
  });

  return response.data.value;
}

function getFileName(nsid: string): string {
  // site.standard.publication -> publication.json
  // site.standard.theme.basic -> theme.basic.json
  const parts = nsid.split(".");
  const name = parts.slice(2).join(".");
  return `${name}.json`;
}

async function main() {
  console.log("Syncing lexicons from AT Protocol...\n");

  if (!existsSync(OUTPUT_DIR)) {
    mkdirSync(OUTPUT_DIR, { recursive: true });
    console.log(`Created directory: ${OUTPUT_DIR}\n`);
  }

  for (const nsid of LEXICONS_TO_SYNC) {
    try {
      console.log(`Fetching ${nsid}...`);
      const lexicon = await fetchLexicon(nsid);
      const fileName = getFileName(nsid);
      const filePath = join(OUTPUT_DIR, fileName);

      writeFileSync(filePath, JSON.stringify(lexicon, null, 2));
      console.log(`  Saved to ${fileName}`);
    } catch (error) {
      console.error(`  Failed to fetch ${nsid}:`, error);
    }
  }

  console.log("\nSync complete.");
}

main();
