import 'server-only';

import { readFile } from 'node:fs/promises';
import path from 'node:path';
import type { CsvTemplateDefinition } from './types';

interface TemplateMetadataFile {
  version: string;
  generatedFrom: string;
  templates: Array<{
    file: string;
    seedType: string;
    importOrder: number;
    supported: boolean;
    requiredColumns: string[];
    description: string;
  }>;
  unsupportedTemplates: string[];
}

export interface CsvTemplateRegistry {
  version: string;
  generatedFrom: string;
  templates: CsvTemplateDefinition[];
  unsupportedTemplates: string[];
}

async function readTemplateHeader(file: string): Promise<string[]> {
  const templatePath = path.join(process.cwd(), 'setup', 'templates', file);
  const text = await readFile(templatePath, 'utf8');
  const [header = ''] = text.replace(/^\uFEFF/, '').split(/\r?\n/);
  return header.split(',').map((column) => column.trim());
}

export async function getCsvTemplateRegistry(): Promise<CsvTemplateRegistry> {
  const metadataPath = path.join(process.cwd(), 'setup', 'templates', 'templates.json');
  const metadata = JSON.parse(await readFile(metadataPath, 'utf8')) as TemplateMetadataFile;

  const templates = await Promise.all(
    metadata.templates.map(async (template) => ({
      ...template,
      template: template.file.replace(/\.csv$/i, ''),
      expectedHeaders: await readTemplateHeader(template.file)
    }))
  );

  return {
    version: metadata.version,
    generatedFrom: metadata.generatedFrom,
    templates,
    unsupportedTemplates: metadata.unsupportedTemplates
  };
}

export function findTemplateByFileName(
  registry: CsvTemplateRegistry,
  fileName: string
): CsvTemplateDefinition | null {
  const normalized = path.basename(fileName).toLowerCase();
  return registry.templates.find((template) => template.file.toLowerCase() === normalized) ?? null;
}

export function isUnsupportedTemplate(registry: CsvTemplateRegistry, fileName: string): boolean {
  const normalized = path.basename(fileName).toLowerCase();
  return registry.unsupportedTemplates.some((template) => template.toLowerCase() === normalized);
}
