/**
 * Skills Types
 *
 * Type definitions for the skills system.
 */

import { z } from 'zod';

/**
 * Skill configuration schema (from SKILL.md frontmatter)
 */
export const SkillConfigSchema = z.object({
  name: z.string().min(1).max(64),
  description: z.string().default(''),
  user_invocable: z.boolean().default(false),
  tools: z.array(z.string()).default([]),
});

export type SkillConfig = z.infer<typeof SkillConfigSchema>;

/**
 * Full skill definition
 */
export interface Skill {
  /** Unique skill identifier */
  name: string;
  /** Description of when to use the skill */
  description: string;
  /** Instructions/prompt for the skill */
  instructions: string;
  /** Required tools for the skill */
  tools: string[];
  /** Whether user can invoke with /name */
  userInvocable: boolean;
  /** Source file path */
  filePath?: string;
  /** Executable scripts in skill directory */
  scripts: string[];
  /** Whether this is a built-in skill */
  builtin: boolean;
}

/**
 * Skill invocation result
 */
export interface SkillInvocation {
  skillName: string;
  description: string;
  instructions: string;
  tools: string[];
  scripts: string[];
  args: string;
}

/**
 * Create skill request
 */
export interface CreateSkillRequest {
  name: string;
  description: string;
  userInvocable?: boolean;
  tools?: string[];
  instructions?: string;
}

/**
 * Skill info response
 */
export interface SkillInfo {
  name: string;
  description: string;
  userInvocable: boolean;
  tools: string[];
  path: string;
  exists: boolean;
  builtin: boolean;
}

/**
 * Validate skill name (lowercase, hyphens, underscores, max 64 chars)
 */
export function isValidSkillName(name: string): boolean {
  return /^[a-z][a-z0-9_-]{0,63}$/.test(name);
}

/**
 * Parse YAML-like frontmatter from skill file
 */
export function parseFrontmatter(content: string): {
  config: Partial<SkillConfig>;
  instructions: string;
} {
  const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);

  if (!frontmatterMatch) {
    return { config: {}, instructions: content.trim() };
  }

  const [, frontmatterStr, instructions] = frontmatterMatch;
  const config: Partial<SkillConfig> = {};

  // Parse simple YAML-like frontmatter
  for (const line of frontmatterStr.split('\n')) {
    const match = line.match(/^(\w+):\s*(.+)$/);
    if (!match) continue;

    const [, key, value] = match;
    const trimmedValue = value.trim();

    switch (key) {
      case 'name':
        config.name = trimmedValue;
        break;
      case 'description':
        config.description = trimmedValue;
        break;
      case 'user_invocable':
        config.user_invocable = trimmedValue === 'true';
        break;
      case 'tools':
        // Parse array: [item1, item2] or item1, item2
        if (trimmedValue.startsWith('[')) {
          config.tools = trimmedValue
            .slice(1, -1)
            .split(',')
            .map((s) => s.trim())
            .filter(Boolean);
        } else {
          config.tools = trimmedValue
            .split(',')
            .map((s) => s.trim())
            .filter(Boolean);
        }
        break;
    }
  }

  return { config, instructions: instructions.trim() };
}

/**
 * Generate SKILL.md content from config
 */
export function generateSkillContent(
  config: SkillConfig,
  instructions: string
): string {
  const lines = [
    '---',
    `name: ${config.name}`,
    `description: ${config.description}`,
    `user_invocable: ${config.user_invocable}`,
  ];

  if (config.tools.length > 0) {
    lines.push(`tools: [${config.tools.join(', ')}]`);
  }

  lines.push('---', '', instructions);

  return lines.join('\n');
}
