// ============================================================
// infrastructure/storage/param-store.ts — 参数历史本地存储
//
// 职责：
//   - 任务提交后保存输入参数快照（task_id 主键）
//   - 任务完成后回填输出数据
//   - 按模型查询历史参数列表（回填菜单数据源）
// ============================================================

import { execute, queryAll, queryOne } from '../core/db-core';
import { getCurrentUserId } from '../services/user-scope';
import type { ParamHistoryEntry } from '../core/types';

const MAX_PER_MODEL = 20;

// ---------- API ----------

export function saveParamSnapshot(
  taskId: string,
  modelId: string,
  modelName: string,
  inputParams: Record<string, unknown>,
  tag?: string,
): void {
  const uid = getCurrentUserId();
  execute(
    `INSERT OR REPLACE INTO param_history (task_id, user_id, model_id, model_name, input_params_json, tag, created_at)
     VALUES (?, ?, ?, ?, ?, ?, ?)`,
    [taskId, uid, modelId, modelName, JSON.stringify(inputParams), tag || null, Date.now()],
  );
  // 裁剪旧记录
  prune(modelId, uid);
}

export function fillOutputData(taskId: string, outputData: Record<string, unknown>): void {
  execute(
    `UPDATE param_history SET output_data_json = ? WHERE task_id = ?`,
    [JSON.stringify(outputData), taskId],
  );
}

export function getParamByTaskId(taskId: string): ParamHistoryEntry | null {
  return queryOne<ParamHistoryEntry>(`SELECT * FROM param_history WHERE task_id = ?`, [taskId]);
}

export function getParamHistory(modelId: string, limit = 10): ParamHistoryEntry[] {
  const uid = getCurrentUserId();
  return queryAll<ParamHistoryEntry>(
    `SELECT * FROM param_history WHERE user_id = ? AND model_id = ? ORDER BY created_at DESC LIMIT ?`,
    [uid, modelId, limit],
  );
}

export function parseParams(entry: ParamHistoryEntry): Record<string, unknown> {
  try { return JSON.parse(entry.input_params_json) as Record<string, unknown>; } catch { return {}; }
}

export function deleteParamHistory(id: number): void {
  execute(`DELETE FROM param_history WHERE id = ?`, [id]);
}

export function clearUserParams(): void {
  execute(`DELETE FROM param_history WHERE user_id = ?`, [getCurrentUserId()]);
}

// ---------- 内部 ----------

function prune(modelId: string, userId: string): void {
  try {
    const rows = queryAll<ParamHistoryEntry>(
      `SELECT id FROM param_history WHERE user_id = ? AND model_id = ? ORDER BY created_at DESC`,
      [userId, modelId],
    );
    if (rows.length <= MAX_PER_MODEL) return;
    const toDelete = rows.slice(MAX_PER_MODEL);
    for (const r of toDelete) {
      if (r.id) execute(`DELETE FROM param_history WHERE id = ?`, [r.id]);
    }
  } catch { /* ignore */ }
}
