/**
 * MockAgentAdapter — PR-26
 *
 * 模拟非 Claw Agent 数据结构，验证 Governance Layer 不依赖 Claw 概念。
 *
 * Mock Agent 结构：
 *   contexts/  — 上下文/分组文件（.md）
 *   threads/   — 线程/对话文件（.md）
 *   archives/  — 归档文件（.md）
 *
 * 映射到统一 Contract：
 *   contexts/  → groups
 *   总文件数    → memoryUnits
 *   非 archives → activeUnits
 *   archives/   → archivedUnits
 *
 * @module mock-adapter
 */

import { AgentAdapter } from "./agent-adapter.mjs";
import { readdirSync, existsSync } from "node:fs";
import { resolve } from "node:path";

const MOCK_DIRS = ["contexts", "threads", "archives"];

/**
 * Mock Agent Adapter
 */
export class MockAgentAdapter extends AgentAdapter {
  getAgentType() {
    return "mock";
  }

  /**
   * 检测 source 是否为 Mock Agent 结构。
   *
   * @param {object|string} source — { basePath } 或路径字符串
   * @returns {boolean}
   */
  detect(source) {
    const basePath = typeof source === "string" ? source : source?.basePath;
    if (!basePath) return false;

    // 检查 contexts/ 目录是否存在（核心标志）
    return existsSync(resolve(basePath, "contexts"));
  }

  /**
   * 从 Mock Agent 数据提取指标。
   *
   * @param {object|string} source — { basePath } 或路径字符串
   * @returns {object} — 符合 AgentContract 格式
   */
  normalize(source) {
    const basePath = typeof source === "string" ? source : source?.basePath;
    if (!basePath) {
      return this._makeContract({ memoryUnits: 0, activeUnits: 0, archivedUnits: 0, groups: 0 });
    }

    // 统计各目录文件数
    const countFiles = (dir) => {
      try {
        return readdirSync(dir).filter(f => f.endsWith(".md")).length;
      } catch { return 0; }
    };

    const contexts = resolve(basePath, "contexts");
    const threads = resolve(basePath, "threads");
    const archives = resolve(basePath, "archives");

    const contextFiles = countFiles(contexts);
    const threadFiles = countFiles(threads);
    const archiveFiles = countFiles(archives);

    // groups = contexts 数
    const groups = contextFiles;

    // memoryUnits = 所有可用文件数
    const memoryUnits = contextFiles + threadFiles + archiveFiles;

    // activeUnits = contexts + threads (非归档)
    const activeUnits = contextFiles + threadFiles;

    // archivedUnits = archives 内的文件
    const archivedUnits = archiveFiles;

    return this._makeContract({
      memoryUnits,
      activeUnits,
      archivedUnits,
      groups,
      sourceVersion: "1.0.0",
      adapterVersion: "1.0.0",
    });
  }
}
