import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { writeFileSync } from 'fs';
import { baseConfig } from '../src/lib/contrail.config';
import { generateLexicons, extractXrpcMethods } from '@atmo-dev/contrail-lexicons';

const ROOT_DIR = join(dirname(fileURLToPath(import.meta.url)), '..');

// Use a config that has spaces/community/realtime declared so the generator
// emits the full surface (space.*, community.*, realtime.*) alongside the
// per-collection endpoints. Values are stubs — only the shape matters for codegen.
const configForGen = {
	...baseConfig,
	spaces: {
		authority: { type: 'tools.atmo.chat.space', serviceDid: 'did:web:localhost' },
		recordHost: {}
	},
	community: { masterKey: new Uint8Array(32), serviceDid: 'did:web:localhost' },
	realtime: { ticketSecret: new Uint8Array(32) }
};

const generated = generateLexicons({
	config: configForGen,
	rootDir: ROOT_DIR,
	outputDir: join(ROOT_DIR, 'lexicons', 'generated'),
	writeRuntimeFiles: true
});

// Emit the sorted XRPC method list as a TS module. settings.ts imports it and
// feeds it into `scope.rpc({ lxm: [...], aud })` so the OAuth consent screen
// requests exactly the methods contrail exposes (no more, no less).
const methods = extractXrpcMethods(generated);
const out = `// Auto-generated by scripts/generate.ts. Do not edit by hand.
// Source of truth: the set of XRPC methods contrail emits for this namespace.

export const xrpcMethods = ${JSON.stringify(methods, null, '\t')} as const;
`;
writeFileSync(join(ROOT_DIR, 'src/lib/atproto/generated-methods.ts'), out);
console.log(`wrote generated-methods.ts (${methods.length} methods)`);
