/**
 * ITTO数据索引
 * 统一导出所有ITTO核心数据
 */

import knowledgeAreasData from './knowledge-areas.json';
import processGroupsData from './process-groups.json';
import processesData from './processes.json';
import artifactsData from './artifacts.json';
import toolsData from './tools.json';
import changelogData from './changelog.json';
import timelineItemsData from './timeline-items.json';

import type {
  KnowledgeArea,
  ProcessGroup,
  Process,
  Artifact,
  ToolTechnique,
  ChangelogEntry,
  DataFlow,
  ProcessRef,
  ProcessEntityUse,
} from '../types/itto';
import type { TimelineItem } from '../types/timeline';

// 导出原始数据
export const knowledgeAreas: KnowledgeArea[] = knowledgeAreasData.knowledgeAreas as KnowledgeArea[];
export const processGroups: ProcessGroup[] = processGroupsData.processGroups as ProcessGroup[];
export const processes: Process[] = processesData.processes as Process[];
export const artifacts: Artifact[] = artifactsData.artifacts as Artifact[];
export const tools: ToolTechnique[] = toolsData.tools as ToolTechnique[];
export const changelogEntries: ChangelogEntry[] = [
  ...(changelogData.changelogEntries as ChangelogEntry[]),
].sort((a, b) => b.date.localeCompare(a.date));

export const timelineItems: TimelineItem[] = [
  ...(timelineItemsData.timelineItems as TimelineItem[]),
].sort((a, b) => a.sortKey.localeCompare(b.sortKey));

// 创建查找映射表
export const knowledgeAreaMap = new Map<string, KnowledgeArea>(
  knowledgeAreas.map(ka => [ka.id, ka])
);

export const processGroupMap = new Map<string, ProcessGroup>(
  processGroups.map(pg => [pg.id, pg])
);

export const processMap = new Map<string, Process>(
  processes.map(p => [p.id, p])
);

export const artifactMap = new Map<string, Artifact>(
  artifacts.map(a => [a.id, a])
);

export const toolMap = new Map<string, ToolTechnique>(
  tools.map(t => [t.id, t])
);

export const timelineItemMap = new Map<string, TimelineItem>(
  timelineItems.map(item => [item.id, item])
);

export const timelineItemsByTheme = new Map<string, TimelineItem[]>();
[...new Set(timelineItems.map(item => item.theme))].forEach(theme => {
  timelineItemsByTheme.set(
    theme,
    timelineItems.filter(item => item.theme === theme)
  );
});

// 按知识领域分组的过程
export const processesByKnowledgeArea = new Map<string, Process[]>();
knowledgeAreas.forEach(ka => {
  processesByKnowledgeArea.set(
    ka.id,
    processes.filter(p => p.knowledgeAreaId === ka.id).sort((a, b) => a.order - b.order)
  );
});

// 按过程组分组的过程
export const processesByProcessGroup = new Map<string, Process[]>();
processGroups.forEach(pg => {
  processesByProcessGroup.set(
    pg.id,
    processes.filter(p => p.processGroupId === pg.id)
  );
});

// 工具函数：规范化 ProcessRef（将字符串或对象统一处理）
export function normalizeProcessRef(ref: ProcessRef): {
  id: string;
  detail?: ProcessEntityUse['detail'];
  note?: string;
} {
  if (typeof ref === 'string') {
    return { id: ref };
  }
  return ref;
}

// 工具函数：从 ProcessRef 中提取 ID
export function extractId(ref: ProcessRef): string {
  return typeof ref === 'string' ? ref : ref.id;
}

// 工具函数：检查 ProcessRef 数组中是否包含某个 ID
export function includesId(refs: ProcessRef[], targetId: string): boolean {
  return refs.some(ref => extractId(ref) === targetId);
}

// 计算数据流向关系
export function computeDataFlows(): DataFlow[] {
  const flows: DataFlow[] = [];

  processes.forEach(sourceProcess => {
    sourceProcess.outputs.forEach(outputRef => {
      const outputId = extractId(outputRef);
      processes.forEach(targetProcess => {
        if (targetProcess.id !== sourceProcess.id && includesId(targetProcess.inputs, outputId)) {
          flows.push({
            sourceProcessId: sourceProcess.id,
            targetProcessId: targetProcess.id,
            artifactId: outputId,
          });
        }
      });
    });
  });

  return flows;
}

// 获取工件的使用情况
export function getArtifactUsage(artifactId: string): {
  asInput: Process[];
  asOutput: Process[];
} {
  return {
    asInput: processes.filter(p => includesId(p.inputs, artifactId)),
    asOutput: processes.filter(p => includesId(p.outputs, artifactId)),
  };
}

// 获取工具的使用情况
export function getToolUsage(toolId: string): Process[] {
  return processes.filter(p => includesId(p.tools, toolId));
}

// 获取过程的完整信息（包含关联数据）
export function getProcessDetail(processId: string) {
  const process = processMap.get(processId);
  if (!process) return null;

  return {
    ...process,
    knowledgeArea: knowledgeAreaMap.get(process.knowledgeAreaId),
    processGroup: processGroupMap.get(process.processGroupId),
    inputDetails: process.inputs.map(ref => {
      const normalized = normalizeProcessRef(ref);
      const artifact = artifactMap.get(normalized.id);
      return artifact ? { ...artifact, detail: normalized.detail, note: normalized.note } : null;
    }).filter(Boolean),
    toolDetails: process.tools.map(ref => {
      const normalized = normalizeProcessRef(ref);
      const tool = toolMap.get(normalized.id);
      return tool ? { ...tool, detail: normalized.detail, note: normalized.note } : null;
    }).filter(Boolean),
    outputDetails: process.outputs.map(ref => {
      const normalized = normalizeProcessRef(ref);
      const artifact = artifactMap.get(normalized.id);
      return artifact ? { ...artifact, detail: normalized.detail, note: normalized.note } : null;
    }).filter(Boolean),
  };
}

// 统计信息
export const stats = {
  knowledgeAreaCount: knowledgeAreas.length,
  processGroupCount: processGroups.length,
  processCount: processes.length,
  artifactCount: artifacts.length,
  toolCount: tools.length,
};
