import { initializeAllContainers, registerContainers } from '@bytelyst/cosmos';
import type { ContainerConfig } from '@bytelyst/cosmos';
import { config } from './config.js';

const CONTAINER_DEFS: Record<string, ContainerConfig> = {
  products: { partitionKeyPath: '/id' },
  users: { partitionKeyPath: '/id' },
  settings: { partitionKeyPath: '/userId' },
  devices: { partitionKeyPath: '/userId' },
  notification_prefs: { partitionKeyPath: '/userId' },
  audit_log: { partitionKeyPath: '/category', defaultTtl: 90 * 86400 },
  feature_flags: { partitionKeyPath: '/id' },
  // Growth modules
  invitation_codes: { partitionKeyPath: '/id' },
  referrals: { partitionKeyPath: '/id' },
  referrals_v2: { partitionKeyPath: '/referrerId' },
  // Billing modules
  subscriptions: { partitionKeyPath: '/userId' },
  payments: { partitionKeyPath: '/userId' },
  licenses: { partitionKeyPath: '/id' },
  plans: { partitionKeyPath: '/id' },
  usage_daily: { partitionKeyPath: '/userId' },
  // API tokens
  api_tokens: { partitionKeyPath: '/id' },
  // Tracker modules
  tracker_items: { partitionKeyPath: '/id' },
  comments: { partitionKeyPath: '/itemId' },
  votes: { partitionKeyPath: '/itemId' },
  // Themes
  themes: { partitionKeyPath: '/id' },
  // Waitlist (pre-launch signups)
  waitlist: { partitionKeyPath: '/email' },
  // Sessions (refresh token rotation + device tracking)
  sessions: { partitionKeyPath: '/userId', defaultTtl: 30 * 86400 },
  // Email/push delivery log
  delivery_log: { partitionKeyPath: '/pk', defaultTtl: 90 * 86400 },
  // Status page incidents
  incidents: { partitionKeyPath: '/productId' },
  // Password reset + email verification
  password_reset_tokens: { partitionKeyPath: '/productId', defaultTtl: 86400 },
  email_verifications: { partitionKeyPath: '/productId', defaultTtl: 7 * 86400 },
  // IP allow/deny rules
  ip_rules: { partitionKeyPath: '/productId' },
  // Data exports
  export_jobs: { partitionKeyPath: '/productId', defaultTtl: 30 * 86400 },
  // Maintenance windows
  maintenance_windows: { partitionKeyPath: '/productId' },
  // Scheduled jobs
  job_definitions: { partitionKeyPath: '/productId' },
  job_runs: { partitionKeyPath: '/productId:jobName' },
  // Telemetry (client diagnostics — see docs/WINDSURF/CLIENT_TELEMETRY_DESIGN.md)
  telemetry_events: { partitionKeyPath: '/pk', defaultTtl: 30 * 86400 },
  telemetry_error_clusters: { partitionKeyPath: '/pk', defaultTtl: 90 * 86400 },
  telemetry_collection_policies: { partitionKeyPath: '/productId' },
  // Database migrations tracking
  migrations: { partitionKeyPath: '/productId' },
  // Webhook subscriptions + delivery log
  webhook_subscriptions: { partitionKeyPath: '/productId' },
  webhook_deliveries: { partitionKeyPath: '/pk', defaultTtl: 30 * 86400 },
  // Generic Marketplace
  marketplace_listings: { partitionKeyPath: '/productId' },
  marketplace_reviews: { partitionKeyPath: '/listingId' },
  marketplace_installs: { partitionKeyPath: '/userId' },
  marketplace_certifications: { partitionKeyPath: '/listingId' },
  marketplace_reports: { partitionKeyPath: '/listingId' },
  marketplace_votes: { partitionKeyPath: '/listingId' },
  // P2 — Product Intelligence
  experiments: { partitionKeyPath: '/id' },
  experiment_assignments: { partitionKeyPath: '/experimentId' },
  // A/B Testing — Extended containers for Intelligent A/B Testing
  ab_testing_variants: { partitionKeyPath: '/experimentId' },
  ab_testing_events: { partitionKeyPath: '/experimentId', defaultTtl: 90 * 86400 },
  ab_testing_metrics: { partitionKeyPath: '/experimentId' },
  experiment_suggestions: { partitionKeyPath: '/productId', defaultTtl: 180 * 86400 },
  analytics_rollups: { partitionKeyPath: '/productId' },
  feedback: { partitionKeyPath: '/productId' },
  impersonation_sessions: { partitionKeyPath: '/productId', defaultTtl: 90 * 86400 },
  changelog: { partitionKeyPath: '/productId' },
  // Remote Diagnostics (see docs/devops/REMOTE_DIAGNOSTICS_ROADMAP.md)
  debug_sessions: { partitionKeyPath: '/id', defaultTtl: 7 * 86400 },
  debug_traces: { partitionKeyPath: '/pk', defaultTtl: 7 * 86400 },
  debug_logs: { partitionKeyPath: '/pk', defaultTtl: 3 * 86400 },
  debug_screenshots: { partitionKeyPath: '/sessionId', defaultTtl: 7 * 86400 },
  diagnostic_triggers: { partitionKeyPath: '/id' },
  session_replays: { partitionKeyPath: '/pk', defaultTtl: 7 * 86400 },
  performance_profiles: { partitionKeyPath: '/pk', defaultTtl: 7 * 86400 },
  // Predictive Analytics
  user_features: { partitionKeyPath: '/userId', defaultTtl: 90 * 86400 },
  product_health: { partitionKeyPath: '/productId' },
  feature_definitions: { partitionKeyPath: '/productId' },
  churn_predictions: { partitionKeyPath: '/userId', defaultTtl: 120 * 86400 },
  retention_campaigns: { partitionKeyPath: '/productId' },
  campaign_deliveries: { partitionKeyPath: '/userId', defaultTtl: 90 * 86400 },
  model_performance: { partitionKeyPath: '/id' },
  // AI Diagnostics (see docs/roadmaps/AI_DIAGNOSTIC_ASSISTANT_ROADMAP.md)
  error_clusters: { partitionKeyPath: '/productId', defaultTtl: 90 * 86400 },
  error_fingerprints: { partitionKeyPath: '/fingerprintHash' },
  diagnostic_insights: { partitionKeyPath: '/clusterId', defaultTtl: 90 * 86400 },
  diagnostic_queries: { partitionKeyPath: '/userId', defaultTtl: 30 * 86400 },
  proactive_alerts: { partitionKeyPath: '/productId', defaultTtl: 30 * 86400 },
  // Broadcast Messaging & Surveys (see docs/roadmaps/not-started/platform_BROADCAST_SURVEY_ROADMAP.md)
  broadcasts: { partitionKeyPath: '/productId' },
  broadcast_deliveries: { partitionKeyPath: '/userId', defaultTtl: 90 * 86400 },
  broadcast_reads: { partitionKeyPath: '/userId', defaultTtl: 90 * 86400 },
  in_app_messages: { partitionKeyPath: '/userId', defaultTtl: 30 * 86400 },
  surveys: { partitionKeyPath: '/productId' },
  survey_responses: { partitionKeyPath: '/surveyId', defaultTtl: 365 * 86400 },
  user_survey_states: { partitionKeyPath: '/userId', defaultTtl: 90 * 86400 },
};

export async function initCosmosIfNeeded(): Promise<void> {
  registerContainers(CONTAINER_DEFS);

  const shouldInit = config.NODE_ENV !== 'production' || process.env.COSMOS_AUTO_INIT === 'true';
  if (!shouldInit) return;

  try {
    await initializeAllContainers();
    process.stdout.write('[platform-service] Cosmos containers ensured\n');
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    process.stderr.write(`[platform-service] Cosmos init failed: ${msg}\n`);
  }
}
