/**
 * 模板 API
 */
import axios from 'axios'
import type { TableStructure, ImageSize, TemplateInfo } from '@/types'

const API_BASE = 'http://localhost:8000/api/templates'

/**
 * 获取模板列表
 */
export async function listTemplates(): Promise<TemplateInfo[]> {
  const response = await axios.get(API_BASE)
  return response.data.templates || []
}

/**
 * 创建模板
 */
export async function createTemplate(
  name: string,
  structure: TableStructure,
  imageSize: ImageSize,
  description: string = ''
): Promise<{ name: string; path: string; stats: object; created_at: string }> {
  const response = await axios.post(API_BASE, {
    name,
    structure,
    image_size: imageSize,
    description
  })
  if (!response.data.success) {
    throw new Error(response.data.detail || '创建模板失败')
  }
  return response.data.data
}

/**
 * 获取模板详情
 */
export async function getTemplate(name: string): Promise<object> {
  const response = await axios.get(`${API_BASE}/${encodeURIComponent(name)}`)
  if (!response.data.success) {
    throw new Error(response.data.detail || '获取模板失败')
  }
  return response.data.data
}

/**
 * 删除模板
 */
export async function deleteTemplate(name: string): Promise<void> {
  const response = await axios.delete(`${API_BASE}/${encodeURIComponent(name)}`)
  if (!response.data.success) {
    throw new Error(response.data.detail || '删除模板失败')
  }
}

/**
 * 预览应用模板
 * @param targetTableBbox 目标页面的 table_bbox，如果提供则将模板映射到此区域
 */
export async function previewApplyTemplate(
  name: string,
  targetImageSize: ImageSize,
  targetTableBbox?: number[] | null,
  mode: 'relative' | 'absolute' = 'relative'
): Promise<TableStructure> {
  const response = await axios.post(`${API_BASE}/${encodeURIComponent(name)}/preview`, {
    target_image_size: targetImageSize,
    target_table_bbox: targetTableBbox,
    mode
  })
  if (!response.data.success) {
    throw new Error(response.data.detail || '预览失败')
  }
  return response.data.data
}

/**
 * 确认应用模板
 * @param targetTableBbox 目标页面的 table_bbox，如果提供则将模板映射到此区域
 */
export async function applyTemplate(
  name: string,
  targetImageSize: ImageSize,
  targetTableBbox?: number[] | null,
  mode: 'relative' | 'absolute' = 'relative'
): Promise<TableStructure> {
  const response = await axios.post(`${API_BASE}/${encodeURIComponent(name)}/apply`, {
    target_image_size: targetImageSize,
    target_table_bbox: targetTableBbox,
    mode
  })
  if (!response.data.success) {
    throw new Error(response.data.detail || '应用模板失败')
  }
  return response.data.data
}
