/**
 * Gitagent Agent
 * Handles: gitagent-detect, gitagent-parse
 *
 * Relay-compatible actions for detecting and parsing gitagent directory structures
 * on the user's local machine.
 */
import fs from 'fs';
import { promises as fsp } from 'fs';
import path from 'path';
import { detectGitagent, parseGitagentRepo } from '../gitagent/parser.js';

/** fs-backed helpers injected into the parser */
async function fsFileExists(filePath) {
  try {
    await fsp.access(filePath, fs.constants.F_OK);
    return true;
  } catch {
    return false;
  }
}

async function fsReadFile(filePath) {
  try {
    return await fsp.readFile(filePath, 'utf8');
  } catch {
    return null;
  }
}

async function fsListDir(dirPath) {
  try {
    return await fsp.readdir(dirPath);
  } catch {
    return [];
  }
}

export default {
  name: 'gitagent',
  actions: {
    /**
     * Lightweight check for agent.yaml existence.
     * @param {{ projectPath: string }} params
     * @returns {{ detected: boolean }}
     */
    'gitagent-detect': async (params) => {
      const projectPath = params.projectPath;
      if (!projectPath) return { detected: false };
      const detected = await detectGitagent(projectPath, fsFileExists);
      return { detected };
    },

    /**
     * Full parse — returns the complete GitagentDefinition as JSON.
     * @param {{ projectPath: string }} params
     * @returns {{ definition: object|null }}
     */
    'gitagent-parse': async (params) => {
      const projectPath = params.projectPath;
      if (!projectPath) return { definition: null };

      const definition = await parseGitagentRepo(projectPath, fsReadFile, fsListDir);
      return { definition };
    },
  },
};
