import { ToolDef } from '../../../llm/openai-compat.js';
import type { ToolContext, ToolResult } from '../core.js';
import { setTheme, type ThemePreset, type ThemeOverrides } from './state.js';

const VALID_PRESETS: ThemePreset[] = [
  'corporate-blue', 'minimal-mono', 'vibrant',
  'academic', 'dark', 'warm-paper',
];

export const SET_THEME_DEF: ToolDef = {
  type: 'function',
  function: {
    name: 'SetTheme',
    description:
      'pptxgenjs スライドのテーマ (色・フォント・サイズ) を選択する。movement 冒頭で 1 回だけ呼ぶ。詳細は ReadToolDoc({ name: "SetTheme" })。',
    parameters: {
      type: 'object',
      properties: {
        preset: { type: 'string', enum: VALID_PRESETS },
        overrides: {
          type: 'object',
          properties: {
            primary: { type: 'string' }, accent: { type: 'string' },
            background: { type: 'string' }, text: { type: 'string' },
            muted: { type: 'string' },
            heading_font: { type: 'string' }, body_font: { type: 'string' },
            title_size: { type: 'number' }, heading_size: { type: 'number' },
            body_size: { type: 'number' },
          },
          additionalProperties: false,
        },
      },
      required: ['preset'],
    },
  },
};

export async function executeSetTheme(
  input: Record<string, unknown>,
  ctx: ToolContext,
): Promise<ToolResult> {
  const preset = input['preset'];
  if (typeof preset !== 'string' || !VALID_PRESETS.includes(preset as ThemePreset)) {
    return {
      output: `SetTheme error: preset must be one of ${VALID_PRESETS.join(', ')}`,
      isError: true,
    };
  }
  const overrides = (input['overrides'] && typeof input['overrides'] === 'object')
    ? input['overrides'] as ThemeOverrides
    : {};
  try {
    setTheme(ctx.workspacePath, { preset: preset as ThemePreset, overrides });
  } catch (e) {
    return { output: `SetTheme error: ${(e as Error).message}`, isError: true };
  }
  return { output: `Theme set to ${preset}.`, isError: false };
}
