// api.ts から分割（挙動不変）: Skills API。
import { buildQuery } from './client';

// ── Skills API ──────────────────────────────────────────────────────────

export interface SkillSummary {
  name: string;
  description: string;
  triggers: string[];
  source: 'system' | 'user';
  hasDir: boolean;
}

export interface SkillDetail extends SkillSummary {
  /** Body only (frontmatter stripped) — for read-only preview. */
  content: string;
  /** Full SKILL.md incl. frontmatter — what the editor must edit/save. */
  raw: string;
  files: string[];
  findings: Array<{ severity: 'medium' | 'high'; pattern: string; match: string; line: number; file?: string }>;
  maxSeverity: 'high' | 'medium' | 'none';
}

export async function fetchSkills(scope?: string, spaceId?: string): Promise<SkillSummary[]> {
  const res = await fetch(`/api/skills${buildQuery({ scope, spaceId })}`);
  if (!res.ok) throw new Error('Failed to fetch skills');
  const data = await res.json();
  return data.skills;
}

export async function fetchSkillDetail(name: string, scope?: string, spaceId?: string): Promise<SkillDetail> {
  const res = await fetch(`/api/skills/${encodeURIComponent(name)}${buildQuery({ scope, spaceId })}`);
  if (!res.ok) throw new Error('Skill not found');
  return res.json();
}

export async function createSkill(name: string, content: string, scope: string, spaceId?: string): Promise<{ name: string; severity: string; findings: any[] }> {
  const res = await fetch(`/api/skills${buildQuery({ spaceId })}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(spaceId ? { name, content, scope, spaceId } : { name, content, scope }),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({ error: 'Unknown error' }));
    throw new Error(err.error);
  }
  return res.json();
}

export async function updateSkill(name: string, content: string, scope: string, spaceId?: string): Promise<any> {
  const res = await fetch(`/api/skills/${encodeURIComponent(name)}${buildQuery({ scope, spaceId })}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(spaceId ? { content, spaceId } : { content }),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({ error: 'Unknown error' }));
    throw new Error(err.error);
  }
  return res.json();
}

export async function deleteSkill(name: string, scope: string, spaceId?: string): Promise<void> {
  const res = await fetch(`/api/skills/${encodeURIComponent(name)}${buildQuery({ scope, spaceId })}`, { method: 'DELETE' });
  if (!res.ok) {
    const err = await res.json().catch(() => ({ error: 'Unknown error' }));
    throw new Error(err.error);
  }
}

export async function installSkillFromUrl(url: string, scope: string, selectedSkills?: string[], spaceId?: string): Promise<any> {
  const res = await fetch(`/api/skills/install-from-url${buildQuery({ spaceId })}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(spaceId ? { url, scope, selectedSkills, spaceId } : { url, scope, selectedSkills }),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({ error: 'Unknown error' }));
    throw new Error(err.error);
  }
  return res.json();
}
