/**
 * Type definitions for Server Recommendation API
 */

export interface Env {
  AI: Ai;  // Legacy - kept for fallback
  DB: D1Database;              // cloud-instances-db: server specs, pricing
  USER_DB: D1Database;         // telegram-conversations: users, deposits, orders
  CACHE: KVNamespace;
  OPENAI_API_KEY: string;
  AI_GATEWAY_URL?: string;  // Cloudflare AI Gateway URL to bypass regional restrictions
  // VPS Provider API Keys
  LINODE_API_KEY?: string;
  VULTR_API_KEY?: string;
  // Provision API security
  PROVISION_API_KEY?: string;  // Required for /api/provision/* endpoints
  // Queue for async provisioning
  PROVISION_QUEUE: Queue<ProvisionQueueMessage>;
}

// Queue message for async server provisioning
// Note: root_password is stored in DB, not in queue message for security
export interface ProvisionQueueMessage {
  order_id: number;
  user_id: number;
  pricing_id: number;
  label: string | null;
  image: string;
  timestamp: string;
}

export interface ValidationError {
  error: string;
  missing_fields?: string[];
  invalid_fields?: { field: string; reason: string }[];
  schema: Record<string, string>;
  example: Record<string, unknown>;
}

export interface RecommendRequest {
  tech_stack: string[];
  expected_users: number;
  use_case: string;
  traffic_pattern?: 'steady' | 'spiky' | 'growing';
  region_preference?: string[];
  budget_limit?: number;
  lang?: 'en' | 'zh' | 'ja' | 'ko'; // Response language
  // CDN options
  cdn_enabled?: boolean;           // CDN 사용 여부 (기본: true - use_case별 자동 추정)
  cdn_cache_hit_rate?: number;     // 캐시 히트율 (0.0-1.0, 기본: use_case별 자동 추정)
}

export interface ExchangeRateCache {
  rate: number;
  timestamp: number;
}

export interface Server {
  id: number;
  provider_name: string;
  instance_id: string;
  instance_name: string;
  vcpu: number;
  memory_mb: number;
  memory_gb: number;
  storage_gb: number;
  network_speed_gbps: number | null;
  instance_family: string | null;
  gpu_count: number;
  gpu_type: string | null;
  monthly_price: number;
  currency: 'USD' | 'KRW';
  region_name: string;
  region_code: string;
  // Transfer pricing (from anvil_instances + anvil_transfer_pricing)
  transfer_tb: number | null;           // 기본 포함 트래픽 (TB/월)
  transfer_price_per_gb: number | null; // 초과 트래픽 가격 ($/GB)
}

export interface BandwidthInfo {
  included_transfer_tb: number;      // 기본 포함 트래픽 (TB/월)
  overage_cost_per_gb: number;       // 초과 비용 ($/GB 또는 ₩/GB)
  overage_cost_per_tb: number;       // 초과 비용 ($/TB 또는 ₩/TB)
  estimated_monthly_tb: number;      // 예상 월간 사용량 (TB) - CDN 적용 후 원본 서버
  estimated_overage_tb: number;      // 예상 초과량 (TB)
  estimated_overage_cost: number;    // 예상 초과 비용
  total_estimated_cost: number;      // 총 예상 비용 (서버 + 트래픽)
  currency: 'USD' | 'KRW';           // 통화
  warning?: string;                  // 트래픽 관련 경고
  // CDN breakdown
  cdn_enabled?: boolean;             // CDN 사용 여부
  cdn_cache_hit_rate?: number;       // CDN 캐시 히트율 (0.0-1.0)
  gross_monthly_tb?: number;         // CDN 적용 전 총 트래픽 (TB)
  cdn_savings_tb?: number;           // CDN으로 절감된 트래픽 (TB)
  cdn_savings_cost?: number;         // CDN으로 절감된 비용
}

export interface AvailableRegion {
  region_name: string;
  region_code: string;
  monthly_price: number;
}

export interface RecommendationResult {
  server: Server;
  score: number;
  analysis: {
    tech_fit: string;
    capacity: string;
    cost_efficiency: string;
    scalability: string;
  };
  estimated_capacity: {
    max_daily_users?: number;
    max_concurrent_users: number;
    requests_per_second: number;
  };
  bandwidth_info?: BandwidthInfo;
  benchmark_reference?: BenchmarkReference;
  vps_benchmark_reference?: {
    plan_name: string;
    geekbench_single: number;
    geekbench_multi: number;
    monthly_price_usd: number;
    performance_per_dollar: number;
  };
  available_regions?: AvailableRegion[];
}

export interface BenchmarkReference {
  processor_name: string;
  benchmarks: {
    name: string;
    category: string;
    score: number;
    percentile: number;
  }[];
}

export interface BenchmarkData {
  id: number;
  processor_name: string;
  benchmark_name: string;
  category: string;
  score: number;
  percentile: number;
  cores: number | null;
}

export interface VPSBenchmark {
  id: number;
  provider_name: string;
  plan_name: string;
  cpu_type: string;
  vcpu: number;
  memory_gb: number;
  country_code: string;
  geekbench_single: number;
  geekbench_multi: number;
  geekbench_total: number;
  monthly_price_usd: number;
  performance_per_dollar: number;
  geekbench_version: string;
  gb6_single_normalized: number;
  gb6_multi_normalized: number;
}

export interface TechSpec {
  id: number;
  name: string;
  category: string;
  vcpu_per_users: number;
  vcpu_per_users_max: number | null;
  min_memory_mb: number;
  max_memory_mb: number | null;
  description: string | null;
  aliases: string | null;
  is_memory_intensive: boolean;
  is_cpu_intensive: boolean;
}

export interface BandwidthEstimate {
  monthly_gb: number;
  monthly_tb: number;
  daily_gb: number;
  category: 'light' | 'moderate' | 'heavy' | 'very_heavy';
  description: string;
  estimated_dau_min: number;  // Daily Active Users estimate (min)
  estimated_dau_max: number;  // Daily Active Users estimate (max)
  active_ratio: number;       // Active user ratio (0.0-1.0)
  // CDN traffic breakdown
  cdn_enabled: boolean;           // CDN 사용 여부
  cdn_cache_hit_rate: number;     // 캐시 히트율 (0.0-1.0)
  gross_monthly_tb: number;       // CDN 적용 전 총 트래픽 (TB)
  origin_monthly_tb: number;      // CDN 적용 후 원본 서버 트래픽 (TB)
}

// Use case configuration for bandwidth estimation and user metrics
export interface UseCaseConfig {
  category: 'video' | 'file' | 'gaming' | 'api' | 'ecommerce' | 'forum' | 'blog' | 'chat' | 'default';
  patterns: RegExp;
  dauMultiplier: { min: number; max: number };
  activeRatio: number;
  cdnCacheHitRate: number;  // 기본 CDN 캐시 히트율 (0.0-1.0)
}

export interface AIRecommendationResponse {
  recommendations: Array<{
    server_id: number;
    score: number;
    analysis: {
      tech_fit: string;
      capacity: string;
      cost_efficiency: string;
      scalability: string;
    };
    estimated_capacity: {
      max_daily_users?: number;
      max_concurrent_users: number;
      requests_per_second: number;
    };
  }>;
  infrastructure_tips?: string[];
}

// ============================================
// Provisioning System Types (telegram-conversations DB)
// ============================================

// users table
export interface TelegramUser {
  id: number;                    // AUTO INCREMENT
  telegram_id: string;           // Telegram user ID (used as external identifier)
  username: string | null;
  first_name: string | null;
  created_at: string;
  updated_at: string;
}

// user_deposits table (balance in KRW, INTEGER)
export interface UserDeposit {
  id: number;
  user_id: number;               // References users.id
  balance: number;               // Balance in KRW (원)
  created_at: string;
  updated_at: string;
}

// server_orders table (existing schema)
export interface ServerOrder {
  id: number;                    // AUTO INCREMENT
  user_id: number;               // References users.id
  spec_id: number;               // Server spec ID
  status: 'pending' | 'provisioning' | 'active' | 'failed' | 'cancelled' | 'terminated';
  region: string;
  provider_instance_id: string | null;
  ip_address: string | null;
  root_password: string | null;
  price_paid: number;            // Price in KRW (원)
  error_message: string | null;
  provisioned_at: string | null;
  terminated_at: string | null;
  created_at: string;
  updated_at: string;
  label: string | null;
  image: string | null;
  billing_type: string;          // 'monthly' default
}

export type VPSProvider = 'linode' | 'vultr';

export interface ProvisionRequest {
  telegram_id: string;           // Telegram user ID
  pricing_id: number;            // From cloud-instances-db.pricing
  label?: string;
  image?: string;                // OS image (e.g., 'ubuntu_22_04')
  dry_run?: boolean;             // Test mode: validate only, don't create server
}

export interface ProvisionResponse {
  success: boolean;
  order?: ServerOrder;
  error?: {
    code: string;
    message: string;
  };
}

// Provider API types
export interface VPSProviderConfig {
  apiKey: string;
  baseUrl: string;
  timeout: number;
}

export interface CreateServerRequest {
  plan: string;           // Provider-specific plan ID (instance_id)
  region: string;         // Provider-specific region code
  osImage: string;        // OS identifier
  label?: string;
  rootPassword: string;
  sshKeys?: string[];
  tags?: string[];
}

export interface CreateServerResponse {
  success: boolean;
  instanceId?: string;
  ipv4?: string;
  ipv6?: string;
  status?: string;
  error?: {
    code: string;
    message: string;
  };
}

export interface PricingWithProvider {
  pricing_id: number;
  provider_id: number;
  provider_name: string;
  api_base_url: string;
  instance_id: string;       // Provider's plan ID (e.g., g6-nanode-1)
  instance_name: string;
  region_code: string;       // Provider's region code
  region_name: string;
  monthly_price: number;
  vcpu: number;
  memory_mb: number;
  storage_gb: number;
}
