// api.ts から分割（挙動不変）: サブタスク（ファイル・進捗）。
import { BASE } from './client';
import type { SubtaskActivity } from './tasks';

// --- Subtasks ---
export interface SubtaskFiles {
  files: string[];
  categories: Record<string, string[]>;
}

export async function fetchSubtaskFiles(taskId: number, jobId: string): Promise<SubtaskFiles> {
  const res = await fetch(`${BASE}/local/tasks/${taskId}/subtasks/${jobId}/files`);
  const data = await res.json();
  if (!res.ok) throw new Error(data?.error ?? 'Failed to fetch subtask files');
  return { files: data.files ?? [], categories: data.categories ?? {} };
}

export function subtaskFileRawUrl(taskId: number, jobId: string, filePath: string): string {
  return `${BASE}/local/tasks/${taskId}/subtasks/${jobId}/files/${filePath}`;
}

export async function fetchSubtaskFileContent(taskId: number, jobId: string, filePath: string): Promise<string> {
  const res = await fetch(subtaskFileRawUrl(taskId, jobId, filePath));
  if (!res.ok) throw new Error('Failed to fetch subtask file content');
  return res.text();
}

export async function fetchSubtaskActivities(taskId: number): Promise<SubtaskActivity[]> {
  const res = await fetch(`${BASE}/local/tasks/${taskId}/subtasks/activities`);
  const data = await res.json();
  if (!res.ok) throw new Error(data?.error ?? 'Failed to fetch subtask activities');
  return data.subtasks ?? [];
}

export async function fetchSubtaskActivity(taskId: number, jobId: string): Promise<string> {
  const res = await fetch(`${BASE}/local/tasks/${taskId}/subtasks/${jobId}/activity`);
  const data = await res.json();
  if (!res.ok) throw new Error(data?.error ?? 'Failed to fetch subtask activity');
  return data.activityLog ?? '';
}
