// src/config/appConfig.ts
import dotenv from 'dotenv';

dotenv.config();

function getRequiredEnv(key: string): string {
  const value = process.env[key];
  if (!value) {
    throw new Error(`Missing required environment variable: ${key}`);
  }
  return value;
}

function getEnvInt(key: string, defaultValue: number): number {
  const value = process.env[key];
  return value ? parseInt(value, 10) : defaultValue;
}

function getEnvFloat(key: string, defaultValue: number): number {
  const value = process.env[key];
  return value ? parseFloat(value) : defaultValue;
}

function getEnvBool(key: string, defaultValue: boolean): boolean {
  const value = process.env[key];
  return value ? value === 'true' : defaultValue;
}

export const config = {
  ai: {
    endpoint: getRequiredEnv('AI_ANALYZER_ENDPOINT'),
    apiKey: getRequiredEnv('AI_ANALYZER_API_KEY'),
    model: getRequiredEnv('AI_ANALYZER_MODEL'),
    maxSelectedItems: getEnvInt('AI_MAX_SELECTED_ITEMS', 25),
    embeddingCandidates: getEnvInt('AI_EMBEDDING_CANDIDATES', 50),
    similarityThreshold: getEnvFloat('AI_SIMILARITY_THRESHOLD', 0.3),
    microTaskDelay: getEnvInt('AI_MICRO_TASK_DELAY_MS', 500),
    embeddingSelectionLimit: getEnvInt('AI_EMBEDDING_SELECTION_LIMIT', 30),
    embeddingConceptsLimit: getEnvInt('AI_EMBEDDING_CONCEPTS_LIMIT', 15),
    noEmbeddingsToolLimit: getEnvInt('AI_NO_EMBEDDINGS_TOOL_LIMIT', 25),
    noEmbeddingsConceptLimit: getEnvInt('AI_NO_EMBEDDINGS_CONCEPT_LIMIT', 10),
    embeddingsMinTools: getEnvInt('AI_EMBEDDINGS_MIN_TOOLS', 8),
    embeddingsMaxReductionRatio: getEnvFloat('AI_EMBEDDINGS_MAX_REDUCTION_RATIO', 0.75),
    methodSelectionRatio: getEnvFloat('AI_METHOD_SELECTION_RATIO', 0.4),
    softwareSelectionRatio: getEnvFloat('AI_SOFTWARE_SELECTION_RATIO', 0.5),
    maxContextTokens: getEnvInt('AI_MAX_CONTEXT_TOKENS', 4000),
    maxPromptTokens: getEnvInt('AI_MAX_PROMPT_TOKENS', 1500),
    taskTimeout: getEnvInt('AI_TASK_TIMEOUT_MS', 300000)
  },
  
  audit: {
    enabled: getEnvBool('FORENSIC_AUDIT_ENABLED', false),
    detailLevel: (process.env.FORENSIC_AUDIT_DETAIL_LEVEL || 'standard') as 'minimal' | 'standard' | 'verbose',
    retentionHours: getEnvInt('FORENSIC_AUDIT_RETENTION_HOURS', 72),
    maxEntries: getEnvInt('FORENSIC_AUDIT_MAX_ENTRIES', 50)
  },
  
  confidence: {
    semanticWeight: getEnvFloat('CONFIDENCE_SEMANTIC_WEIGHT', 0.3),
    suitabilityWeight: getEnvFloat('CONFIDENCE_SUITABILITY_WEIGHT', 0.7),
    minimumThreshold: getEnvInt('CONFIDENCE_MINIMUM_THRESHOLD', 40),
    mediumThreshold: getEnvInt('CONFIDENCE_MEDIUM_THRESHOLD', 60),
    highThreshold: getEnvInt('CONFIDENCE_HIGH_THRESHOLD', 80)
  },
  
  rateLimit: {
    delayMs: getEnvInt('AI_RATE_LIMIT_DELAY_MS', 2000),
    window: 60 * 1000, // 1 minute
    maxRequests: getEnvInt('AI_RATE_LIMIT_MAX_REQUESTS', 4),
    microTaskTotalLimit: getEnvInt('AI_MICRO_TASK_TOTAL_LIMIT', 50)
  }
} as const;

export type AppConfig = typeof config;