import 'dotenv/config'
import { getDb } from '../index.js'
import { logger } from '../../lib/logger.js'

interface ServiceDefinition {
  name: string
  slug: string
  category: string
  description: string
  shortDescription: string
  tags: string[]
  featured: boolean
  iconUrl?: string
  documentationUrl?: string
  supportUrl?: string
  metadata: Record<string, any>
  pricingType: string
  pricingConfig: {
    basePrice?: number
    currency?: string
    billingPeriod?: string
    usageRates?: Record<string, any>
    freeTier?: {
      requestsPerMonth?: number
      features?: string[]
    }
  }
}

const services: ServiceDefinition[] = [
  {
    name: 'Phoenix Ledger Service',
    slug: 'phoenix-ledger-service',
    category: 'LEDGER_SERVICES',
    description: `A sovereign-grade double-entry ledger system with virtual accounts, holds, and multi-asset support. 
    Replaces reliance on external platforms (e.g., Tatum Virtual Accounts) with owned core primitives. 
    Features include journal entries, subaccounts, holds/reserves, reconciliation, and full audit trail. 
    Every transaction is a balanced journal entry with idempotency via correlation_id. 
    Supports multi-asset operations (fiat, stablecoins, tokens) with state machine-based settlement.`,
    shortDescription: 'Double-entry ledger with virtual accounts, holds, and multi-asset support',
    tags: ['ledger', 'double-entry', 'virtual-accounts', 'financial', 'sovereign', 'audit'],
    featured: true,
    iconUrl: 'https://cdn.sankofa.nexus/services/ledger.svg',
    documentationUrl: 'https://docs.sankofa.nexus/services/ledger',
    supportUrl: 'https://support.sankofa.nexus/ledger',
    metadata: {
      apiEndpoints: [
        'POST /ledger/entries',
        'POST /ledger/holds',
        'POST /ledger/transfers',
        'GET /ledger/balances'
      ],
      features: [
        'Double-entry accounting',
        'Virtual account abstraction',
        'Holds and reserves',
        'Multi-asset support',
        'Reconciliation engine',
        'Immutable audit trail',
        'Idempotent operations',
        'State machine settlement'
      ],
      compliance: ['SOC 2', 'PCI DSS', 'GDPR'],
      providerAdapters: [],
      sla: {
        uptime: '99.9%',
        latency: '<100ms p95'
      },
      architecture: 'docs/marketplace/sovereign-stack/ledger-service.md'
    },
    pricingType: 'USAGE_BASED',
    pricingConfig: {
      currency: 'USD',
      usageRates: {
        journalEntry: 0.001,
        holdOperation: 0.0005,
        transfer: 0.002
      },
      freeTier: {
        requestsPerMonth: 10000,
        features: ['Basic ledger operations', 'Up to 100 virtual accounts']
      }
    }
  },
  {
    name: 'Phoenix Identity Service',
    slug: 'phoenix-identity-service',
    category: 'IDENTITY_SERVICES',
    description: `Comprehensive identity, authentication, and authorization service with support for users, organizations, 
    roles, and permissions. Features device binding, passkeys support, OAuth/OpenID Connect for integrations, 
    session management, and risk scoring. Centralizes identity management with no provider dependencies. 
    Supports multi-tenant identity with fine-grained RBAC and sovereign identity principles.`,
    shortDescription: 'Users, orgs, roles, permissions, device binding, passkeys, OAuth/OIDC',
    tags: ['identity', 'auth', 'rbac', 'oauth', 'oidc', 'passkeys', 'sovereign'],
    featured: true,
    iconUrl: 'https://cdn.sankofa.nexus/services/identity.svg',
    documentationUrl: 'https://docs.sankofa.nexus/services/identity',
    supportUrl: 'https://support.sankofa.nexus/identity',
    metadata: {
      apiEndpoints: [
        'POST /identity/users',
        'POST /identity/orgs',
        'GET /identity/sessions',
        'POST /identity/auth/token'
      ],
      features: [
        'Multi-tenant identity',
        'RBAC with fine-grained permissions',
        'Device binding',
        'Passkeys support',
        'OAuth 2.0 / OIDC',
        'Session management',
        'Risk scoring',
        'SCIM support'
      ],
      compliance: ['SOC 2', 'GDPR', 'HIPAA'],
      providerAdapters: [],
      sla: {
        uptime: '99.95%',
        latency: '<50ms p95'
      },
      architecture: 'docs/marketplace/sovereign-stack/identity-service.md'
    },
    pricingType: 'SUBSCRIPTION',
    pricingConfig: {
      basePrice: 99,
      currency: 'USD',
      billingPeriod: 'MONTHLY',
      usageRates: {
        perUser: 2.50,
        perOrg: 50.00
      }
    }
  },
  {
    name: 'Phoenix Wallet Registry',
    slug: 'phoenix-wallet-registry',
    category: 'WALLET_SERVICES',
    description: `Wallet mapping and signing policy service with chain support matrix and policy engine. 
    Manages wallet mapping (user/org ↔ wallet addresses), chain support, policy engine for signing limits and approvals, 
    and recovery policies. Supports MPC (preferred for production custody), HSM-backed keys for service wallets, 
    and passkeys + account abstraction for end-users. Features transaction simulation and ERC-4337 smart accounts.`,
    shortDescription: 'Wallet mapping, chain support, policy engine, recovery, MPC, HSM',
    tags: ['wallet', 'blockchain', 'mpc', 'hsm', 'erc4337', 'custody', 'signing'],
    featured: true,
    iconUrl: 'https://cdn.sankofa.nexus/services/wallet.svg',
    documentationUrl: 'https://docs.sankofa.nexus/services/wallet',
    supportUrl: 'https://support.sankofa.nexus/wallet',
    metadata: {
      apiEndpoints: [
        'POST /wallets/register',
        'POST /wallets/tx/build',
        'POST /wallets/tx/simulate',
        'POST /wallets/tx/submit'
      ],
      features: [
        'Wallet mapping and registry',
        'Multi-chain support',
        'MPC custody',
        'HSM-backed keys',
        'Transaction simulation',
        'ERC-4337 smart accounts',
        'Policy engine',
        'Recovery policies'
      ],
      compliance: ['SOC 2', 'ISO 27001'],
      providerAdapters: ['Thirdweb (optional)'],
      sla: {
        uptime: '99.9%',
        latency: '<200ms p95'
      },
      architecture: 'docs/marketplace/sovereign-stack/wallet-registry.md'
    },
    pricingType: 'HYBRID',
    pricingConfig: {
      basePrice: 199,
      currency: 'USD',
      billingPeriod: 'MONTHLY',
      usageRates: {
        perWallet: 5.00,
        perTransaction: 0.01
      }
    }
  },
  {
    name: 'Phoenix Transaction Orchestrator',
    slug: 'phoenix-tx-orchestrator',
    category: 'ORCHESTRATION_SERVICES',
    description: `On-chain and off-chain workflow orchestration service with retries, compensations, 
    provider routing, and fallback. Implements state machines for workflow management, enforces idempotency 
    and exactly-once semantics (logical), and provides provider routing with automatic failover. 
    Supports both on-chain blockchain transactions and off-chain operations with unified orchestration.`,
    shortDescription: 'On-chain/off-chain workflow orchestration with retries and compensations',
    tags: ['orchestration', 'workflow', 'blockchain', 'state-machine', 'idempotency', 'transactions'],
    featured: true,
    iconUrl: 'https://cdn.sankofa.nexus/services/tx-orchestrator.svg',
    documentationUrl: 'https://docs.sankofa.nexus/services/tx-orchestrator',
    supportUrl: 'https://support.sankofa.nexus/tx-orchestrator',
    metadata: {
      apiEndpoints: [
        'POST /orchestrator/workflows',
        'GET /orchestrator/workflows/{id}',
        'POST /orchestrator/workflows/{id}/retry'
      ],
      features: [
        'Workflow state machines',
        'Retries and compensations',
        'Provider routing and fallback',
        'Idempotency enforcement',
        'Exactly-once semantics',
        'On-chain and off-chain support',
        'Correlation ID tracking'
      ],
      compliance: ['SOC 2'],
      providerAdapters: ['Alchemy', 'Infura', 'Self-hosted nodes'],
      sla: {
        uptime: '99.9%',
        latency: '<500ms p95'
      },
      architecture: 'docs/marketplace/sovereign-stack/tx-orchestrator.md'
    },
    pricingType: 'USAGE_BASED',
    pricingConfig: {
      currency: 'USD',
      usageRates: {
        perTransaction: 0.05,
        perWorkflow: 0.10
      },
      freeTier: {
        requestsPerMonth: 1000,
        features: ['Basic orchestration', 'Up to 10 concurrent workflows']
      }
    }
  },
  {
    name: 'Phoenix Messaging Orchestrator',
    slug: 'phoenix-messaging-orchestrator',
    category: 'ORCHESTRATION_SERVICES',
    description: `Multi-provider messaging orchestration service with failover for SMS, voice, email, and push notifications. 
    Features provider selection rules based on cost, deliverability, region, and user preference. 
    Includes delivery receipts, retries, suppression lists, and compliance features. 
    Replaces reliance on Twilio with owned core primitives while retaining optional provider integrations via adapters.`,
    shortDescription: 'Multi-provider messaging (SMS/voice/email/push) with failover',
    tags: ['messaging', 'sms', 'email', 'push', 'notifications', 'orchestration', 'failover'],
    featured: true,
    iconUrl: 'https://cdn.sankofa.nexus/services/messaging.svg',
    documentationUrl: 'https://docs.sankofa.nexus/services/messaging',
    supportUrl: 'https://support.sankofa.nexus/messaging',
    metadata: {
      apiEndpoints: [
        'POST /messages/send',
        'GET /messages/status/{id}',
        'GET /messages/delivery/{id}'
      ],
      features: [
        'Multi-provider routing',
        'Automatic failover',
        'Delivery receipts',
        'Retry logic',
        'Suppression lists',
        'Template management',
        'Compliance features',
        'Cost optimization'
      ],
      compliance: ['SOC 2', 'GDPR', 'TCPA'],
      providerAdapters: ['Twilio', 'AWS SNS', 'Vonage', 'MessageBird'],
      sla: {
        uptime: '99.9%',
        latency: '<200ms p95'
      },
      architecture: 'docs/marketplace/sovereign-stack/messaging-orchestrator.md'
    },
    pricingType: 'USAGE_BASED',
    pricingConfig: {
      currency: 'USD',
      usageRates: {
        perSMS: 0.01,
        perEmail: 0.001,
        perPush: 0.0005,
        perVoice: 0.02
      },
      freeTier: {
        requestsPerMonth: 1000,
        features: ['Basic messaging', 'Single provider']
      }
    }
  },
  {
    name: 'Phoenix Voice Orchestrator',
    slug: 'phoenix-voice-orchestrator',
    category: 'ORCHESTRATION_SERVICES',
    description: `Text-to-speech and speech-to-text orchestration service with audio caching, 
    multi-provider routing, and moderation. Features deterministic caching (hash-based) for cost and latency optimization, 
    PII scrubbing, multi-model routing for high quality vs low-latency scenarios, and OSS fallback path for baseline TTS. 
    Replaces reliance on ElevenLabs with owned core primitives while retaining optional provider integrations.`,
    shortDescription: 'TTS/STT with caching, multi-provider routing, moderation',
    tags: ['voice', 'tts', 'stt', 'audio', 'media', 'orchestration', 'ai'],
    featured: true,
    iconUrl: 'https://cdn.sankofa.nexus/services/voice.svg',
    documentationUrl: 'https://docs.sankofa.nexus/services/voice',
    supportUrl: 'https://support.sankofa.nexus/voice',
    metadata: {
      apiEndpoints: [
        'POST /voice/synthesize',
        'GET /voice/audio/{hash}',
        'POST /voice/transcribe'
      ],
      features: [
        'Audio caching',
        'Multi-provider routing',
        'PII scrubbing',
        'Moderation',
        'Multi-model support',
        'OSS fallback',
        'CDN delivery'
      ],
      compliance: ['SOC 2', 'GDPR'],
      providerAdapters: ['ElevenLabs', 'OpenAI', 'Azure TTS', 'OSS TTS'],
      sla: {
        uptime: '99.9%',
        latency: '<500ms p95'
      },
      architecture: 'docs/marketplace/sovereign-stack/voice-orchestrator.md'
    },
    pricingType: 'USAGE_BASED',
    pricingConfig: {
      currency: 'USD',
      usageRates: {
        perSynthesis: 0.02,
        perMinute: 0.10,
        perTranscription: 0.05
      },
      freeTier: {
        requestsPerMonth: 100,
        features: ['Basic TTS/STT', 'Standard quality']
      }
    }
  },
  {
    name: 'Phoenix Event Bus',
    slug: 'phoenix-event-bus',
    category: 'PLATFORM_SERVICES',
    description: `Durable event bus service with replay, versioning, and consumer idempotency. 
    Implements DB Outbox pattern for atomic state + event writes. Supports Kafka, Redpanda, and NATS backends. 
    Features event versioning, consumer offset tracking, and processed correlation ID tracking for exactly-once delivery.`,
    shortDescription: 'Durable events, replay, versioning, consumer idempotency',
    tags: ['events', 'messaging', 'kafka', 'outbox', 'event-sourcing', 'platform'],
    featured: false,
    iconUrl: 'https://cdn.sankofa.nexus/services/event-bus.svg',
    documentationUrl: 'https://docs.sankofa.nexus/services/event-bus',
    supportUrl: 'https://support.sankofa.nexus/event-bus',
    metadata: {
      apiEndpoints: [
        'POST /events/publish',
        'GET /events/consume',
        'POST /events/replay'
      ],
      features: [
        'DB Outbox pattern',
        'Event versioning',
        'Consumer idempotency',
        'Replay support',
        'Multiple backends (Kafka/Redpanda/NATS)',
        'Offset tracking',
        'Correlation ID support'
      ],
      compliance: ['SOC 2'],
      providerAdapters: ['Kafka', 'Redpanda', 'NATS'],
      sla: {
        uptime: '99.95%',
        latency: '<100ms p95'
      },
      architecture: 'docs/marketplace/sovereign-stack/event-bus.md'
    },
    pricingType: 'SUBSCRIPTION',
    pricingConfig: {
      basePrice: 149,
      currency: 'USD',
      billingPeriod: 'MONTHLY',
      usageRates: {
        perGBStorage: 0.10,
        perMillionEvents: 5.00
      }
    }
  },
  {
    name: 'Phoenix Audit Service',
    slug: 'phoenix-audit-service',
    category: 'PLATFORM_SERVICES',
    description: `Immutable audit logging service with WORM (Write Once Read Many) archive for compliance. 
    Features immutable audit logs with who-did-what-when tracking, PII boundaries and retention policies, 
    and separate operational DB from analytics store. Uses CDC to stream into warehouse for compliance reporting.`,
    shortDescription: 'Immutable audit logs, WORM archive, PII boundaries, compliance',
    tags: ['audit', 'logging', 'compliance', 'worm', 'immutable', 'platform'],
    featured: false,
    iconUrl: 'https://cdn.sankofa.nexus/services/audit.svg',
    documentationUrl: 'https://docs.sankofa.nexus/services/audit',
    supportUrl: 'https://support.sankofa.nexus/audit',
    metadata: {
      apiEndpoints: [
        'POST /audit/log',
        'GET /audit/query',
        'GET /audit/export'
      ],
      features: [
        'Immutable logs',
        'WORM archive',
        'PII boundaries',
        'Retention policies',
        'Compliance reporting',
        'Access trails',
        'CDC to warehouse'
      ],
      compliance: ['SOC 2', 'GDPR', 'HIPAA', 'PCI DSS'],
      providerAdapters: [],
      sla: {
        uptime: '99.9%',
        latency: '<50ms p95'
      },
      architecture: 'docs/marketplace/sovereign-stack/audit-service.md'
    },
    pricingType: 'USAGE_BASED',
    pricingConfig: {
      currency: 'USD',
      usageRates: {
        perGBStorage: 0.15,
        perMillionLogs: 10.00
      },
      freeTier: {
        requestsPerMonth: 100000,
        features: ['Basic audit logging', '30-day retention']
      }
    }
  },
  {
    name: 'Phoenix Observability Stack',
    slug: 'phoenix-observability',
    category: 'PLATFORM_SERVICES',
    description: `Comprehensive observability service with distributed tracing, structured logs with correlation IDs, 
    and SLO monitoring. Features OpenTelemetry integration, distributed tracing across services, 
    SLOs for ledger posting, message delivery, and transaction settlement. Provides structured logging 
    with correlation IDs for end-to-end request tracking.`,
    shortDescription: 'Distributed tracing, structured logs, SLOs, correlation IDs',
    tags: ['observability', 'monitoring', 'tracing', 'logging', 'slo', 'opentelemetry', 'platform'],
    featured: false,
    iconUrl: 'https://cdn.sankofa.nexus/services/observability.svg',
    documentationUrl: 'https://docs.sankofa.nexus/services/observability',
    supportUrl: 'https://support.sankofa.nexus/observability',
    metadata: {
      apiEndpoints: [
        'GET /observability/traces',
        'GET /observability/metrics',
        'GET /observability/logs',
        'GET /observability/slos'
      ],
      features: [
        'Distributed tracing',
        'OpenTelemetry integration',
        'Structured logging',
        'Correlation IDs',
        'SLO monitoring',
        'Metrics collection',
        'Alerting'
      ],
      compliance: ['SOC 2'],
      providerAdapters: [],
      sla: {
        uptime: '99.9%',
        latency: '<100ms p95'
      },
      architecture: 'docs/marketplace/sovereign-stack/observability.md'
    },
    pricingType: 'USAGE_BASED',
    pricingConfig: {
      currency: 'USD',
      usageRates: {
        perMetric: 0.0001,
        perLog: 0.00005,
        perTrace: 0.001
      },
      freeTier: {
        requestsPerMonth: 1000000,
        features: ['Basic observability', '7-day retention']
      }
    }
  }
]

async function seedSovereignStackServices() {
  const db = getDb()

  try {
    logger.info('Seeding Sovereign Stack services...')

    // Get or create Phoenix publisher
    const publisherResult = await db.query(
      `SELECT id FROM publishers WHERE name = 'phoenix-cloud-services'`
    )

    if (publisherResult.rows.length === 0) {
      throw new Error('Phoenix publisher not found. Please run migration 025 first.')
    }

    const publisherId = publisherResult.rows[0].id
    logger.info(`✓ Found Phoenix publisher: ${publisherId}`)

    // Seed each service
    for (const service of services) {
      // Create product
      const productResult = await db.query(
        `INSERT INTO products (
          name, slug, category, description, short_description, publisher_id,
          status, featured, icon_url, documentation_url, support_url, metadata, tags
        ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
        ON CONFLICT (slug) DO UPDATE SET
          name = EXCLUDED.name,
          description = EXCLUDED.description,
          short_description = EXCLUDED.description,
          category = EXCLUDED.category,
          featured = EXCLUDED.featured,
          icon_url = EXCLUDED.icon_url,
          documentation_url = EXCLUDED.documentation_url,
          support_url = EXCLUDED.support_url,
          metadata = EXCLUDED.metadata,
          tags = EXCLUDED.tags,
          updated_at = NOW()
        RETURNING id`,
        [
          service.name,
          service.slug,
          service.category,
          service.description,
          service.shortDescription,
          publisherId,
          'PUBLISHED',
          service.featured,
          service.iconUrl || null,
          service.documentationUrl || null,
          service.supportUrl || null,
          JSON.stringify(service.metadata),
          service.tags
        ]
      )

      const productId = productResult.rows[0].id
      logger.info(`✓ Created/updated product: ${service.name} (${productId})`)

      // Create product version (v1.0.0)
      const versionResult = await db.query(
        `INSERT INTO product_versions (
          product_id, version, status, is_latest, released_at, metadata
        ) VALUES ($1, $2, $3, $4, $5, $6)
        ON CONFLICT (product_id, version) DO UPDATE SET
          status = EXCLUDED.status,
          is_latest = EXCLUDED.is_latest,
          released_at = EXCLUDED.released_at,
          updated_at = NOW()
        RETURNING id`,
        [
          productId,
          '1.0.0',
          'PUBLISHED',
          true,
          new Date(),
          JSON.stringify({ initialRelease: true })
        ]
      )

      const versionId = versionResult.rows[0].id

      // Unmark other versions as latest
      await db.query(
        `UPDATE product_versions 
         SET is_latest = FALSE 
         WHERE product_id = $1 AND id != $2`,
        [productId, versionId]
      )

      // Create pricing model
      await db.query(
        `INSERT INTO pricing_models (
          product_id, product_version_id, pricing_type, base_price, currency, 
          billing_period, usage_rates, metadata
        ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
        ON CONFLICT DO NOTHING`,
        [
          productId,
          versionId,
          service.pricingType,
          service.pricingConfig.basePrice || null,
          service.pricingConfig.currency || 'USD',
          service.pricingConfig.billingPeriod || null,
          JSON.stringify(service.pricingConfig.usageRates || {}),
          JSON.stringify({
            freeTier: service.pricingConfig.freeTier || null,
            ...service.pricingConfig
          })
        ]
      )

      logger.info(`✓ Created pricing model for: ${service.name}`)
    }

    logger.info(`✓ Successfully seeded ${services.length} Sovereign Stack services!`)
  } catch (error) {
    logger.error('Seeding error', { error })
    throw error
  } finally {
    await db.end()
  }
}

// Run if called directly (check if this is the main module)
const isMainModule = import.meta.url === `file://${process.argv[1]}` || 
                     process.argv[1]?.includes('sovereign_stack_services') ||
                     process.argv[1]?.endsWith('sovereign_stack_services.ts')

if (isMainModule) {
  seedSovereignStackServices().catch((error) => {
    logger.error('Failed to seed Sovereign Stack services', { error })
    process.exit(1)
  })
}

export { seedSovereignStackServices, services }
