/**
 * Knowledge-graph display labels – Chinese translations for node types and
 * relationship types used in the Neo4j knowledge graph.
 *
 * All core data sources are Vue `reactive()` objects so that downstream
 * components (GraphExplorer, card panels, etc.) automatically react when
 * `loadTypesFromApi()` merges API-reported types at runtime.
 */

import { reactive, computed } from 'vue'

// ---------------------------------------------------------------------------
// Default (hardcoded) data — used as initial values before API loads
// ---------------------------------------------------------------------------

const DEFAULT_NODE_TYPE_COLORS: Record<string, string> = {
  // Core display
  Document:       '#1677ff',
  // Phase 0 – governance
  Organization:   '#52c41a',
  Region:         '#f5222d',
  PolicyTheme:    '#722ed1',
  // Phase 0 – new core entities
  Policy:         '#9254de',
  Task:           '#ff7a45',
  Project:        '#36cfc9',
  System:         '#597ef7',
  DataResource:   '#73d13d',
  Indicator:      '#ffc53d',
  Budget:         '#ff4d4f',
  Industry:       '#bae637',
  // Phase 1 – matters
  Matter:         '#fa8c16',
  Condition:      '#a0d911',
  Material:       '#13c2c2',
  TimeLimit:      '#eb2f96',
  TargetGroup:    '#1890ff',
  // Phase 3 – office extension
  Person:         '#faad14',
  Event:          '#ff85c0',
  Mechanism:      '#87e8de',
  Standard:       '#d3adf7',
  Infrastructure: '#95de64',
  Technology:     '#69c0ff',
}

const DEFAULT_NODE_TYPE_ZH: Record<string, string> = {
  Document:       '公文',
  // Phase 0 – governance
  Organization:   '机构',
  Region:         '地域',
  PolicyTheme:    '政策主题',
  // Phase 0 – new core
  Policy:         '政策措施',
  Task:           '工作任务',
  Project:        '项目',
  System:         '系统/平台',
  DataResource:   '数据资源',
  Indicator:      '指标',
  Budget:         '预算/资金',
  Industry:       '产业/行业',
  // Phase 1 – matters
  Matter:         '事项',
  Condition:      '条件',
  Material:       '材料',
  TimeLimit:      '时限',
  TargetGroup:    '适用对象',
  // Phase 3 – office extension
  Person:         '人员',
  Event:          '事件',
  Mechanism:      '机制',
  Standard:       '标准',
  Infrastructure: '基础设施',
  Technology:     '技术',
}

const DEFAULT_REL_TYPE_ZH: Record<string, string> = {
  // Phase 0 – governance (existing)
  ISSUED_BY:          '发布机构',
  APPLIES_TO_REGION:  '适用地域',
  BELONGS_TO_THEME:   '属于主题',
  BASED_ON:           '依据',
  AMENDS:             '修订',
  REPEALS:            '废止',
  REFERENCES:         '引用',
  GOVERNS:            '规范事项',
  // Phase 1 – matters
  HAS_CONDITION:      '适用条件',
  REQUIRES_MATERIAL:  '所需材料',
  HAS_TIME_LIMIT:     '办理时限',
  APPLIES_TO_TARGET:  '适用对象',
  HANDLED_BY:         '办理机构',
  // Phase 0 – new core relationships
  CONTAINS_POLICY:    '包含政策',
  DEPLOYS_TASK:       '部署任务',
  APPROVES_PROJECT:   '批准项目',
  LEAD_BY:            '牵头单位',
  ASSISTED_BY:        '配合单位',
  ASSIGNED_TO:        '责任单位',
  IMPLEMENTED_BY:     '实施单位',
  OPERATED_BY:        '运营单位',
  SUBORDINATE_TO:     '隶属',
  COOPERATES_WITH:    '合作',
  RELATES_TO_THEME:   '关联主题',
  IMPLEMENTS:         '落实',
  LOCATED_IN:         '所在区域',
  SUPPORTED_BY:       '政策支持',
  FUNDS:              '资助',
  MANAGES:            '管理',
  EVALUATES:          '考核',
  // Phase 3 – office extension relationships
  SERVES_IN:          '任职于',
  LEADS:              '主管',
  INSTRUCTS:          '批示',
  CONTACTS_FOR:       '联系人',
  HELD_BY:            '举办',
  CHAIRED_BY:         '主持',
  ATTENDED_BY:        '参加',
  PRODUCES:           '产出',
  DECIDES:            '决定',
  HELD_IN:            '举办地点',
  ESTABLISHED_BY:     '建立',
  MECHANISM_MANAGED_BY: '管理机制',
  APPLIES_TO:         '适用',
  STIPULATED_BY:      '规定',
  CONFORMED_BY:       '遵从',
  INFRA_MANAGED_BY:   '管理设施',
  HOSTS:              '承载',
  COVERS:             '覆盖',
  USES_TECH:          '使用技术',
  INDUSTRY_SUPPORTED_BY: '产业支持',
  INDUSTRY_LOCATED_IN:   '产业所在',
  INDUSTRY_MANAGED_BY:   '产业管理',
  // Legacy (backward compat)
  ISSUED:             '发文',
  RECEIVED_BY:        '收文',
  SIGNED:             '签发',
  HANDLED:            '承办',
  INVOLVES:           '涉及',
  COVERS_REGION:      '涉及地区',
  ABOUT:              '主题',
  CATEGORIZED_AS:     '文种',
  TAGGED:             '主题词',
  RELATED_TO:         '关联',
}

// ---------------------------------------------------------------------------
// Reactive data sources — Vue tracks mutations to these objects
// ---------------------------------------------------------------------------

export const nodeTypeState = reactive({
  colors: { ...DEFAULT_NODE_TYPE_COLORS } as Record<string, string>,
  zhNames: { ...DEFAULT_NODE_TYPE_ZH } as Record<string, string>,
  /** label → key_property mapping, e.g. { Person: "person_id" } */
  keyProperties: {} as Record<string, string>,
})

export const relTypeState = reactive({
  zhNames: { ...DEFAULT_REL_TYPE_ZH } as Record<string, string>,
})

// ---------------------------------------------------------------------------
// Backward-compatible exports — these reference the reactive inner objects
// so existing code like `NODE_TYPE_COLORS['Policy']` still works AND is
// reactive when used inside Vue computed / render contexts.
// ---------------------------------------------------------------------------

export const NODE_TYPE_COLORS = nodeTypeState.colors
export const NODE_TYPE_ZH = nodeTypeState.zhNames
export const REL_TYPE_ZH = relTypeState.zhNames

// ---------------------------------------------------------------------------
// Computed derived list — auto-updates when nodeTypeState changes
// Output shape: { label, value, color } — consumed by GraphExplorer filters
// ---------------------------------------------------------------------------

export const NODE_TYPE_LIST = computed(() =>
  Object.entries(nodeTypeState.zhNames).map(([value, label]) => ({
    label,
    value,
    color: nodeTypeState.colors[value] || '#8c8c8c',
  })),
)

// ---------------------------------------------------------------------------
// Lookup helpers
// ---------------------------------------------------------------------------

/** Chinese label for a node type. Falls back to original label. */
export function getNodeTypeZh(label: string): string {
  return nodeTypeState.zhNames[label] || label
}

/** Chinese label for a relationship type. Falls back to original type. */
export function getRelTypeZh(relType: string): string {
  return relTypeState.zhNames[relType] || relType
}

/** Display color for a node label. */
export function getNodeColor(label: string): string {
  return nodeTypeState.colors[label] || '#8c8c8c'
}

// ---------------------------------------------------------------------------
// Dynamic type loading from admin API
// ---------------------------------------------------------------------------

/**
 * Load entity/relationship type definitions from the admin API and merge
 * into the reactive lookup maps. Uses zh_name (preferred) or description
 * as the display label. Preserves existing hardcoded entries as fallback.
 * Call once at app startup or when types change.
 */
export async function loadTypesFromApi(): Promise<void> {
  try {
    const { listEntityTypes, listRelTypes } = await import('@/api/admin-graph')
    const [etResp, rtResp] = await Promise.all([listEntityTypes(), listRelTypes()])

    for (const et of etResp.items) {
      // Color: always update from API (schema is authoritative)
      if (et.color) {
        nodeTypeState.colors[et.name] = et.color
      }
      // zh_name preferred, fallback to description
      const zhLabel = et.zh_name || et.description
      if (zhLabel) {
        nodeTypeState.zhNames[et.name] = zhLabel
      }
      // key_property mapping (e.g. Person → person_id)
      if (et.key_property) {
        nodeTypeState.keyProperties[et.name] = et.key_property
      }
    }
    for (const rt of rtResp.items) {
      const zhLabel = rt.zh_name || rt.description
      if (zhLabel) {
        relTypeState.zhNames[rt.name] = zhLabel
      }
    }
  } catch {
    // Silently fall back to hardcoded defaults
  }
}
