import { VOCAB } from '@/lib/white-label/constants';

/**
 * ${VOCAB.factory} Configuration
 * 
 * This configuration system allows ${VOCAB.factory} to run in three modes:
 * - 'standalone': Independent product with own auth and branding
 * - 'integrated': Part of GFS with shared auth
 * - 'both': Accessible both ways (default)
 */

export type DarkFactoryMode = 'standalone' | 'integrated' | 'both';

export interface DarkFactoryBranding {
  name: string;
  tagline: string;
  logo: string;
  favicon: string;
  primaryColor: string;
  accentColor: string;
  darkBackground: string;
}

export interface GFSIntegrationConfig {
  enabled: boolean;
  apiEndpoint?: string;
  sharedAuth: boolean;
  syncEvents: boolean;
  unifiedBilling: boolean;
}

export interface DarkFactoryFeatures {
  sandbox: boolean;
  deployment: boolean;
  teamManagement: boolean;
  apiAccess: boolean;
  webhooks: boolean;
  whiteLabel: boolean;
  customPatterns: boolean;
}

export interface DarkFactoryLimits {
  freeGenerationsPerMonth: number;
  proGenerationsPerMonth: number;
  teamGenerationsPerMonth: number;
  maxProjectsPerUser: number;
  maxTeamMembers: number;
  apiRateLimitPerMinute: number;
}

export interface DarkFactoryOutputConfig {
  /** Base directory for generated project outputs */
  baseDir: string;
  /** Whether to write artifacts to filesystem (vs just DB storage) */
  writeToFilesystem: boolean;
  /** Template directory for scaffolding new projects */
  templateDir: string;
}

export interface DarkFactoryConfig {
  mode: DarkFactoryMode;
  version: string;
  branding: DarkFactoryBranding;
  gfs: GFSIntegrationConfig;
  features: DarkFactoryFeatures;
  limits: DarkFactoryLimits;
  output: DarkFactoryOutputConfig;
  urls: {
    standalone: string;
    integrated: string;
    api: string;
    docs: string;
  };
}

/**
 * Get the current ${VOCAB.factory} configuration
 * Reads from environment variables with sensible defaults
 */
export function getDarkFactoryConfig(): DarkFactoryConfig {
  return {
    mode: (process.env.DARK_FACTORY_MODE as DarkFactoryMode) || 'both',
    version: '1.0.0',
    
    branding: {
      name: process.env.DF_BRAND_NAME || VOCAB.factory,
      tagline: process.env.DF_TAGLINE || 'The AI Factory That Builds Itself',
      logo: process.env.DF_LOGO_URL || '/dark-factory/logo.svg',
      favicon: process.env.DF_FAVICON_URL || '/dark-factory/favicon.svg',
      primaryColor: process.env.DF_PRIMARY_COLOR || '#0EA5E9', // cyan-500
      accentColor: process.env.DF_ACCENT_COLOR || '#a855f7',   // purple-500
      darkBackground: process.env.DF_BG_COLOR || '#0C1222',
    },
    
    gfs: {
      enabled: process.env.GFS_INTEGRATION !== 'false',
      apiEndpoint: process.env.GFS_API_ENDPOINT || '/api/gfs',
      sharedAuth: process.env.GFS_SHARED_AUTH !== 'false',
      syncEvents: process.env.GFS_SYNC_EVENTS !== 'false',
      unifiedBilling: process.env.GFS_UNIFIED_BILLING !== 'false',
    },
    
    features: {
      sandbox: process.env.DF_FEATURE_SANDBOX !== 'false',
      deployment: process.env.DF_FEATURE_DEPLOYMENT !== 'false',
      teamManagement: process.env.DF_FEATURE_TEAMS !== 'false',
      apiAccess: process.env.DF_FEATURE_API !== 'false',
      webhooks: process.env.DF_FEATURE_WEBHOOKS !== 'false',
      whiteLabel: process.env.DF_FEATURE_WHITELABEL === 'true',
      customPatterns: process.env.DF_FEATURE_PATTERNS !== 'false',
    },
    
    limits: {
      freeGenerationsPerMonth: parseInt(process.env.DF_LIMIT_FREE || '50'),
      proGenerationsPerMonth: parseInt(process.env.DF_LIMIT_PRO || '500'),
      teamGenerationsPerMonth: parseInt(process.env.DF_LIMIT_TEAM || '2000'),
      maxProjectsPerUser: parseInt(process.env.DF_LIMIT_PROJECTS || '10'),
      maxTeamMembers: parseInt(process.env.DF_LIMIT_TEAM_MEMBERS || '20'),
      apiRateLimitPerMinute: parseInt(process.env.DF_RATE_LIMIT || '60'),
    },
    
    output: {
      // Option C (Hybrid): DF engine lives in GFS, outputs stored in DB + data dir
      // In dev: ./data/df-outputs, in prod: artifacts stored in database
      baseDir: process.env.DF_OUTPUT_DIR || './data/df-outputs',
      writeToFilesystem: process.env.NODE_ENV === 'development',
      templateDir: './data/df-templates',
    },
    
    urls: {
      standalone: '/dark-factory',
      integrated: '/ghost-control/dark-factory',
      api: '/api/dark-factory',
      docs: '/dark-factory/docs',
    },
  };
}

/**
 * Check if ${VOCAB.factory} is accessible in standalone mode
 */
export function isStandaloneEnabled(): boolean {
  const config = getDarkFactoryConfig();
  return config.mode === 'standalone' || config.mode === 'both';
}

/**
 * Check if ${VOCAB.factory} is accessible via GFS integration
 */
export function isIntegratedEnabled(): boolean {
  const config = getDarkFactoryConfig();
  return (config.mode === 'integrated' || config.mode === 'both') && config.gfs.enabled;
}

/**
 * Get the appropriate entry URL based on mode and context
 */
export function getEntryUrl(preferIntegrated: boolean = false): string {
  const config = getDarkFactoryConfig();
  
  if (preferIntegrated && isIntegratedEnabled()) {
    return config.urls.integrated;
  }
  
  if (isStandaloneEnabled()) {
    return config.urls.standalone;
  }
  
  return config.urls.integrated;
}

/**
 * Get the output directory for a specific project
 */
export function getProjectOutputDir(projectId: string): string {
  const config = getDarkFactoryConfig();
  return `${config.output.baseDir}/${projectId}`;
}

/**
 * Get all output paths for a project
 */
export function getProjectPaths(projectId: string): {
  root: string;
  src: string;
  api: string;
  components: string;
  prisma: string;
  tests: string;
} {
  const root = getProjectOutputDir(projectId);
  return {
    root,
    src: `${root}/src`,
    api: `${root}/src/api`,
    components: `${root}/src/components`,
    prisma: `${root}/prisma`,
    tests: `${root}/tests`,
  };
}

// Export singleton config for easy access
export const dfConfig = getDarkFactoryConfig();
