import { readdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { PrismaClient } from '@prisma/client';
import yaml from 'js-yaml';
import { seedTemplates } from '@mcpctl/db';
import type { SeedTemplate } from '@mcpctl/db';

function loadTemplatesFromDir(dir: string): SeedTemplate[] {
  let files: string[];
  try {
    files = readdirSync(dir).filter((f) => f.endsWith('.yaml') || f.endsWith('.yml'));
  } catch {
    console.warn(`Templates directory not found: ${dir}`);
    return [];
  }

  const templates: SeedTemplate[] = [];
  for (const file of files) {
    const content = readFileSync(join(dir, file), 'utf-8');
    const parsed = yaml.load(content) as SeedTemplate;
    if (parsed?.name) {
      templates.push({
        ...parsed,
        transport: parsed.transport ?? 'STDIO',
        version: parsed.version ?? '1.0.0',
        description: parsed.description ?? '',
        ...(parsed.healthCheck ? { healthCheck: parsed.healthCheck } : {}),
      });
    }
  }

  return templates;
}

async function run(): Promise<void> {
  const prisma = new PrismaClient();
  try {
    // Look for templates in common locations
    const templatesDir = process.env.TEMPLATES_DIR ?? 'templates';
    const templates = loadTemplatesFromDir(templatesDir);
    const count = await seedTemplates(prisma, templates);
    console.log(`Seeded ${count} templates from ${templatesDir}`);
  } finally {
    await prisma.$disconnect();
  }
}

run().catch((err) => {
  console.error('Seed failed:', err);
  process.exit(1);
});
