/**
 * useTopologyData — 從 dashboard store 讀取真實資料，轉換為 React Flow 節點/邊線
 * ==================================================================================
 * Sprint 5 Phase 2: 串接真實 /api/v1/dashboard API
 *
 * 資料來源:
 *   - useDashboardStore → hosts[] (真實 TCP/HTTP 探測結果)
 *   - 每個 host 包含: ip, name, role, status, services[], metrics
 *
 * 零假數據: 所有節點資料來自 HostAggregator 真實探測
 *
 * 建立時間: 2026-04-08 (台北時區)
 * 建立者: Claude Code (Sprint 5 Phase 2)
 */

import { useMemo } from 'react'
import { useDashboardStore, type Host, type HostService } from '@/stores/dashboard.store'
import type { Node, Edge } from '@xyflow/react'

// =============================================================================
// 群組配置 (對應 host_aggregator.py HostRole)
// =============================================================================

// C2: 群組標籤用 key 而非硬編碼中文（i18n 在元件層處理）
const GROUP_CONFIG: Record<string, { labelKey: string; color: string; borderColor: string; bgColor: string }> = {
  devops:   { labelKey: 'infra',    color: '#3B82F6', borderColor: 'rgba(59,130,246,0.25)',  bgColor: 'rgba(59,130,246,0.02)' },
  security: { labelKey: 'security', color: '#cc2200', borderColor: 'rgba(204,34,0,0.25)',    bgColor: 'rgba(204,34,0,0.02)' },
  k3s:      { labelKey: 'k3s',      color: '#A855F7', borderColor: 'rgba(168,85,247,0.25)',  bgColor: 'rgba(168,85,247,0.02)' },
  ai_web:   { labelKey: 'aiData',   color: '#F97316', borderColor: 'rgba(249,115,22,0.25)',  bgColor: 'rgba(249,115,22,0.02)' },
}

// =============================================================================
// 服務間依賴關係 (靜態定義，對應 ConfigMap 環境變數)
// 來源: config.py DATABASE_URL/REDIS_URL/OLLAMA_URL/OPENCLAW_URL + Sentry SDK
// =============================================================================

const SERVICE_DEPENDENCIES: [string, string][] = [
  // K3s → AI/數據
  ['awoooi-api', 'PostgreSQL'],
  ['awoooi-api', 'Redis'],
  ['awoooi-api', 'OpenClaw'],
  ['awoooi-worker', 'PostgreSQL'],
  ['awoooi-worker', 'Redis'],
  ['awoooi-worker', 'Ollama'],
  // AI 內部
  ['OpenClaw', 'Ollama'],
  ['OpenClaw', 'Redis'],
  // 監控
  ['SigNoz', 'ClickHouse'],
  // DevOps
  ['awoooi-api', 'Sentry'],
  ['awoooi-web', 'Sentry'],
]

// =============================================================================
// Hook
// =============================================================================

export interface TopologyData {
  nodes: Node[]
  edges: Edge[]
  hostCount: number
  serviceCount: number
  healthyCount: number
  warningCount: number
}

export function useTopologyData(): TopologyData {
  const hosts = useDashboardStore(s => s.hosts)

  return useMemo(() => {
    const nodes: Node[] = []
    const edges: Edge[] = []
    let serviceCount = 0
    let healthyCount = 0
    let warningCount = 0

    // 群組節點 + 服務節點
    hosts.forEach((host, hostIdx) => {
      const groupId = `group-${host.ip}`
      const config = GROUP_CONFIG[host.role] || GROUP_CONFIG.devops

      // 群組節點
      nodes.push({
        id: groupId,
        type: 'groupNode',
        position: { x: (hostIdx % 2) * 350, y: Math.floor(hostIdx / 2) * 300 },
        data: {
          labelKey: config.labelKey,
        ipSuffix: host.ip.split('.').pop(),
          role: host.role,
          status: host.status,
          ip: host.ip,
          hostName: host.name,
          serviceCount: host.services.length,
          healthyServices: host.services.filter(s => s.status === 'up').length,
          metrics: host.metrics,
          color: config.color,
          borderColor: config.borderColor,
          bgColor: config.bgColor,
        },
      })

      // 服務節點
      host.services.forEach((svc, svcIdx) => {
        const svcId = `svc-${host.ip}-${svc.name}`
        serviceCount++

        if (svc.status === 'up') healthyCount++
        else warningCount++

        nodes.push({
          id: svcId,
          type: 'serviceNode',
          parentId: groupId,
          position: { x: (svcIdx % 3) * 140 + 10, y: Math.floor(svcIdx / 3) * 50 + 60 },
          data: {
            name: svc.name,
            status: svc.status,
            port: svc.port,
            latency: svc.latency_ms,
            error: svc.error,
            hostIp: host.ip,
          },
        })
      })
    })

    // 依賴邊線 (只連接存在的服務)
    const nodeIds = new Set(nodes.map(n => n.id))
    SERVICE_DEPENDENCIES.forEach(([fromName, toName]) => {
      // 找到來源和目標節點
      const fromNode = nodes.find(n => n.type === 'serviceNode' && n.data.name === fromName)
      const toNode = nodes.find(n => n.type === 'serviceNode' && n.data.name === toName)

      if (fromNode && toNode) {
        edges.push({
          id: `edge-${fromNode.id}-${toNode.id}`,
          source: fromNode.id,
          target: toNode.id,
          type: 'topologyEdge',
          data: {
            status: fromNode.data.status === 'up' && toNode.data.status === 'up' ? 'healthy' : 'warning',
          },
        })
      }
    })

    return {
      nodes,
      edges,
      hostCount: hosts.length,
      serviceCount,
      healthyCount,
      warningCount,
    }
  }, [hosts])
}
