/**
 * Feature flag seeding — creates default flags per product on startup.
 *
 * Idempotent: skips flags that already exist (matched by key + productId).
 * Called from server startup after Cosmos init.
 */

import * as repo from './repository.js';
import type { FeatureFlagDoc } from './types.js';

interface FlagSeedDef {
  key: string;
  enabled: boolean;
  description: string;
  platforms: string[];
  percentage: number;
}

// ─── Default flags per product ───────────────────────────────────────────────

const COMMON_FLAGS: FlagSeedDef[] = [
  {
    key: 'maintenance_mode',
    enabled: false,
    description: 'Global maintenance mode — disables non-essential features',
    platforms: [],
    percentage: 100,
  },
  {
    key: 'telemetry_enabled',
    enabled: true,
    description: 'Client telemetry collection enabled',
    platforms: [],
    percentage: 100,
  },
  {
    key: 'encryption_enabled',
    enabled: true,
    description:
      'Field-level encryption at rest — disable to store plaintext (e.g., for debugging)',
    platforms: [],
    percentage: 100,
  },
];

const PRODUCT_FLAGS: Record<string, FlagSeedDef[]> = {
  chronomind: [
    {
      key: 'routines_enabled',
      enabled: true,
      description: 'Routines feature visible in navigation',
      platforms: ['web', 'ios', 'android'],
      percentage: 100,
    },
    {
      key: 'focus_mode_enabled',
      enabled: true,
      description: 'Pomodoro / focus mode available',
      platforms: ['web', 'ios', 'android'],
      percentage: 100,
    },
    {
      key: 'calendar_import_enabled',
      enabled: true,
      description: 'Calendar .ics import feature',
      platforms: ['web'],
      percentage: 100,
    },
    {
      key: 'cloud_sync_enabled',
      enabled: false,
      description: 'Cloud sync for timers and routines',
      platforms: [],
      percentage: 0,
    },
  ],
  nomgap: [
    {
      key: 'ai_coach_enabled',
      enabled: false,
      description: 'AI coaching card on fasting screen (Pro feature)',
      platforms: ['ios', 'android'],
      percentage: 0,
    },
    {
      key: 'social_fasting_enabled',
      enabled: false,
      description: 'Social fasting / group fasts',
      platforms: ['ios', 'android'],
      percentage: 0,
    },
    {
      key: 'meal_logging_enabled',
      enabled: true,
      description: 'Meal logging before/after fasts',
      platforms: ['ios', 'android'],
      percentage: 100,
    },
    {
      key: 'anatomical_mode_enabled',
      enabled: false,
      description: 'Anatomical body visualization (Pro)',
      platforms: ['ios', 'android'],
      percentage: 0,
    },
    {
      key: 'push_triggers.enabled',
      enabled: true,
      description: 'Server-side push notification triggers',
      platforms: ['ios', 'android'],
      percentage: 100,
    },
  ],
  mindlyst: [
    {
      key: 'voice_capture_enabled',
      enabled: true,
      description: 'Voice capture / transcription',
      platforms: ['ios', 'android'],
      percentage: 100,
    },
    {
      key: 'ai_triage_enabled',
      enabled: true,
      description: 'AI auto-triage into brains',
      platforms: ['ios', 'android', 'web'],
      percentage: 100,
    },
    {
      key: 'share_cards_enabled',
      enabled: false,
      description: 'Shareable memory cards',
      platforms: [],
      percentage: 0,
    },
  ],
  smartauth: [
    {
      key: 'smartauth.oneauth.enabled',
      enabled: false,
      description: 'OneAuth unified identity — cross-product user lookup + membership provisioning',
      platforms: [],
      percentage: 0,
    },
    {
      key: 'smartauth.oauth.google',
      enabled: false,
      description: 'Google OAuth sign-in',
      platforms: [],
      percentage: 0,
    },
    {
      key: 'smartauth.oauth.microsoft',
      enabled: false,
      description: 'Microsoft OAuth sign-in',
      platforms: [],
      percentage: 0,
    },
    {
      key: 'smartauth.oauth.apple',
      enabled: false,
      description: 'Apple OAuth sign-in',
      platforms: [],
      percentage: 0,
    },
    {
      key: 'smartauth.mfa.totp',
      enabled: false,
      description: 'TOTP MFA setup and verification',
      platforms: [],
      percentage: 0,
    },
    {
      key: 'smartauth.passkeys',
      enabled: false,
      description: 'WebAuthn passkey registration and authentication',
      platforms: [],
      percentage: 0,
    },
    {
      key: 'smartauth.device_trust',
      enabled: false,
      description: 'Device trust — fingerprinting + trust levels + MFA skip',
      platforms: [],
      percentage: 0,
    },
    {
      key: 'smartauth.risk_scoring',
      enabled: false,
      description: 'Login event risk scoring + suspicious login detection',
      platforms: [],
      percentage: 0,
    },
    {
      key: 'smartauth.step_up',
      enabled: false,
      description: 'Step-up authentication for sensitive operations',
      platforms: [],
      percentage: 0,
    },
    {
      key: 'smartauth.rs256',
      enabled: false,
      description: 'RS256 JWT signing (migration from HS256)',
      platforms: [],
      percentage: 0,
    },
    {
      key: 'smartauth.push_mfa',
      enabled: false,
      description: 'Push notification MFA',
      platforms: [],
      percentage: 0,
    },
    {
      key: 'smartauth.qr_auth',
      enabled: false,
      description: 'QR code authentication',
      platforms: [],
      percentage: 0,
    },
    {
      key: 'smartauth.saml',
      enabled: false,
      description: 'Enterprise SAML 2.0 + OIDC federation',
      platforms: [],
      percentage: 0,
    },
  ],
  lysnrai: [
    {
      key: 'keyboard_dictation_enabled',
      enabled: true,
      description: 'Keyboard extension dictation',
      platforms: ['ios'],
      percentage: 100,
    },
    {
      key: 'smart_punctuation_enabled',
      enabled: true,
      description: 'Smart punctuation in dictation',
      platforms: ['ios', 'desktop'],
      percentage: 100,
    },
    {
      key: 'speak_to_translate_enabled',
      enabled: false,
      description: 'Speak-to-translate mode (requires Azure Translator)',
      platforms: ['ios'],
      percentage: 0,
    },
  ],
  jarvisjr: [
    {
      key: 'voice_sessions_enabled',
      enabled: true,
      description: 'Voice-first coaching sessions',
      platforms: ['ios', 'web'],
      percentage: 100,
    },
    {
      key: 'agent_marketplace_enabled',
      enabled: false,
      description: 'Agent marketplace browse and purchase',
      platforms: ['ios', 'web'],
      percentage: 0,
    },
    {
      key: 'agent_memory_enabled',
      enabled: true,
      description: 'Per-agent persistent memory',
      platforms: ['ios', 'web'],
      percentage: 100,
    },
  ],
  peakpulse: [
    {
      key: 'live_activity_enabled',
      enabled: true,
      description: 'Dynamic Island + Lock Screen live activity',
      platforms: ['ios'],
      percentage: 100,
    },
    {
      key: 'ski_intelligence_enabled',
      enabled: true,
      description: 'Ski run detection and speed zones',
      platforms: ['ios'],
      percentage: 100,
    },
    {
      key: 'cloud_sync_enabled',
      enabled: false,
      description: 'Cloud sync for sessions',
      platforms: [],
      percentage: 0,
    },
  ],
  flowmonk: [
    {
      key: 'agent_recommendations_enabled',
      enabled: true,
      description: 'AI agent scheduling recommendations',
      platforms: ['web', 'mobile'],
      percentage: 100,
    },
    {
      key: 'schedule_sse_enabled',
      enabled: true,
      description: 'Real-time schedule updates via SSE',
      platforms: ['web'],
      percentage: 100,
    },
  ],
  notelett: [
    {
      key: 'mcp_tools_enabled',
      enabled: true,
      description: 'MCP tool integration for AI agents',
      platforms: [],
      percentage: 100,
    },
    {
      key: 'note_artifacts_enabled',
      enabled: true,
      description: 'File/artifact attachments on notes',
      platforms: ['web', 'mobile'],
      percentage: 100,
    },
  ],
  actiontrail: [
    {
      key: 'trace_explorer_enabled',
      enabled: true,
      description: 'Trace grouping and explorer UI',
      platforms: ['web'],
      percentage: 100,
    },
    {
      key: 'webhook_dispatch_enabled',
      enabled: true,
      description: 'Webhook event dispatch to subscribers',
      platforms: [],
      percentage: 100,
    },
  ],
  localmemgpt: [
    {
      key: 'multi_model_compare_enabled',
      enabled: true,
      description: 'Multi-model compare (SSE)',
      platforms: ['web'],
      percentage: 100,
    },
    {
      key: 'rag_documents_enabled',
      enabled: true,
      description: 'RAG document upload and retrieval',
      platforms: ['web'],
      percentage: 100,
    },
  ],
  devintelli: [
    {
      key: 'devintelli_enabled',
      enabled: true,
      description: 'Master switch for DevIntelli product features',
      platforms: ['web'],
      percentage: 100,
    },
    {
      key: 'devintelli_scan_enabled',
      enabled: true,
      description: 'GitHub PAT scanning and data ingestion',
      platforms: ['web'],
      percentage: 100,
    },
    {
      key: 'devintelli_daily_sync',
      enabled: true,
      description: 'Scheduled daily incremental sync of GitHub data',
      platforms: [],
      percentage: 100,
    },
    {
      key: 'devintelli_overview_panel',
      enabled: true,
      description: 'Dashboard overview panel (stats, heatmap, streak)',
      platforms: ['web'],
      percentage: 100,
    },
    {
      key: 'devintelli_commit_panel',
      enabled: true,
      description: 'Commit Intelligence analytics panel',
      platforms: ['web'],
      percentage: 100,
    },
    {
      key: 'devintelli_pr_panel',
      enabled: true,
      description: 'Pull Request analytics panel',
      platforms: ['web'],
      percentage: 100,
    },
    {
      key: 'devintelli_review_panel',
      enabled: true,
      description: 'Code Review Activity analytics panel',
      platforms: ['web'],
      percentage: 100,
    },
    {
      key: 'devintelli_language_panel',
      enabled: true,
      description: 'Language & Tech Profile analytics panel',
      platforms: ['web'],
      percentage: 100,
    },
    {
      key: 'devintelli_productivity_panel',
      enabled: true,
      description: 'Productivity Patterns analytics panel',
      platforms: ['web'],
      percentage: 100,
    },
    {
      key: 'devintelli_repo_panel',
      enabled: true,
      description: 'Repository analytics panel',
      platforms: ['web'],
      percentage: 100,
    },
    {
      key: 'devintelli_billing_enabled',
      enabled: false,
      description: 'Billing / subscription features (Pro tier)',
      platforms: ['web'],
      percentage: 0,
    },
  ],
  clawcowork: [
    {
      key: 'sandbox_enabled',
      enabled: true,
      description: 'Docker sandbox for agent task execution',
      platforms: ['macos', 'linux', 'windows'],
      percentage: 100,
    },
    {
      key: 'plugins_enabled',
      enabled: true,
      description: 'Plugin system (load, execute, manage plugins)',
      platforms: ['macos', 'linux', 'windows'],
      percentage: 100,
    },
    {
      key: 'mcp_connectors_enabled',
      enabled: true,
      description: 'MCP connector integration (Google Drive, Gmail, Slack, etc.)',
      platforms: ['macos', 'linux', 'windows'],
      percentage: 100,
    },
    {
      key: 'scheduling_enabled',
      enabled: true,
      description: 'Task scheduler (cron, interval, file-watch triggers)',
      platforms: ['macos', 'linux', 'windows'],
      percentage: 100,
    },
    {
      key: 'computer_use_enabled',
      enabled: false,
      description: 'Computer Use — screenshot, click, type automation (requires explicit opt-in)',
      platforms: ['macos'],
      percentage: 0,
    },
    {
      key: 'parallel_agents_enabled',
      enabled: true,
      description: 'Parallel sub-agent execution for complex tasks',
      platforms: ['macos', 'linux', 'windows'],
      percentage: 100,
    },
    {
      key: 'marketplace_enabled',
      enabled: true,
      description: 'Plugin marketplace (browse, install, update)',
      platforms: ['macos', 'linux', 'windows'],
      percentage: 100,
    },
    {
      key: 'wasm_plugins_enabled',
      enabled: false,
      description: 'WASM plugin runtime via wasmtime/wasmer (experimental)',
      platforms: ['macos', 'linux'],
      percentage: 0,
    },
    {
      key: 'llm_multi_model_enabled',
      enabled: false,
      description: 'Multi-model LLM routing (planner/executor/reviewer role assignment)',
      platforms: [],
      percentage: 0,
    },
    {
      key: 'audit_logging_enabled',
      enabled: true,
      description: 'Agent action audit trail',
      platforms: ['macos', 'linux', 'windows'],
      percentage: 100,
    },
    {
      key: 'platform_auth_required',
      enabled: false,
      description: 'Require platform JWT auth — when false, offline API key fallback allowed',
      platforms: [],
      percentage: 0,
    },
    {
      key: 'dispatch_api_enabled',
      enabled: true,
      description: 'Remote task dispatch REST API + WebSocket streaming',
      platforms: ['macos', 'linux', 'windows'],
      percentage: 100,
    },
  ],
};

// ─── Seed function ───────────────────────────────────────────────────────────

export async function seedDefaultFlags(logger?: { info: (msg: string) => void }): Promise<number> {
  const log = logger ?? { info: () => {} };
  let created = 0;

  const products = Object.keys(PRODUCT_FLAGS);

  for (const productId of products) {
    const flags = [...COMMON_FLAGS, ...PRODUCT_FLAGS[productId]];

    for (const def of flags) {
      const existing = await repo.getByKey(def.key, productId);
      if (existing) continue;

      const now = new Date().toISOString();
      const doc: FeatureFlagDoc = {
        id: `flag_${productId}_${def.key}`,
        productId,
        key: def.key,
        flagType: 'boolean',
        enabled: def.enabled,
        archived: false,
        description: def.description,
        tags: [],
        variations: [
          { key: 'on', value: true, description: 'Flag is on' },
          { key: 'off', value: false, description: 'Flag is off' },
        ],
        defaultVariation: 'on',
        offVariation: 'off',
        platforms: def.platforms,
        regions: [],
        osVersions: [],
        segments: [],
        targetingRules: [],
        individualTargets: {},
        prerequisites: [],
        percentage: def.percentage,
        createdAt: now,
        updatedAt: now,
        createdBy: 'system',
        updatedBy: 'system',
        version: 1,
      };

      await repo.create(doc);
      created++;
      log.info(`Seeded flag: ${productId}/${def.key} (enabled=${def.enabled})`);
    }
  }

  if (created > 0) {
    log.info(`Feature flag seeding complete: ${created} flags created`);
  }

  return created;
}
