import fs from 'node:fs';
import path from 'node:path';
import { AGENTS_DIR } from './paths.js';

function assertSafeAgentId(id) {
  const value = String(id || '').trim();
  if (!/^[a-z0-9][a-z0-9-]{0,120}$/i.test(value)) throw new Error('invalid agent id');
  return value;
}

export function agentSkillsPath(id) {
  const safeId = assertSafeAgentId(id);
  const file = path.resolve(AGENTS_DIR, safeId, 'skills.md');
  const root = path.resolve(AGENTS_DIR);
  const relative = path.relative(root, file);
  if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) throw new Error('invalid agent id');
  return file;
}

export function defaultAgentSkillsTemplate(agent = {}) {
  const name = String(agent.name || 'Agent').trim() || 'Agent';
  const mission = String(agent.mission || 'Support madarX OS operations.').trim();
  const tools = Array.isArray(agent.tools) && agent.tools.length
    ? agent.tools.map(tool => `- ${tool}`).join('\n')
    : '- No explicit tools assigned yet.';
  return `# ${name} Skills

## Mission context
${mission}

## Core playbooks
- Convert ambiguous owner requests into a short plan, then execute with visible checkpoints.
- Keep outputs presentation-first: concise, operator-ready, and linked to artifacts when useful.
- Preserve current functionality unless the owner explicitly asks for a behavior change.

## Available tools
${tools}

## Approval workflow
- Read-only discovery can proceed when permitted by tool permissions.
- File writes, terminal commands, deploys, external sends, and destructive actions require explicit approval.
- If an approval is denied or expires, stop and summarize the safest next action.

## Quality bar
- Prefer test-first implementation for code changes.
- Run focused verification before full quality gates.
- Record useful findings in artifacts or memory only when durable.
`;
}

export function readAgentSkills(id) {
  try { return fs.readFileSync(agentSkillsPath(id), 'utf8'); } catch { return ''; }
}

export function writeAgentSkills(id, content) {
  const text = String(content ?? '').slice(0, 200_000);
  const file = agentSkillsPath(id);
  fs.mkdirSync(path.dirname(file), { recursive: true });
  fs.writeFileSync(file, text, 'utf8');
  return text;
}
