// ═══════════════════════════════════════════════════════════════════════
// Strategy Customization API Client
// ═══════════════════════════════════════════════════════════════════════

import { resolveBackendUrl } from "../backendUrl";
import type {
  ParamsSchemaResponse,
  StrategyParamsResponse,
  ParamsValidateResponse,
  ParamsApplyResponse,
  StrategyHistoryResponse,
  StrategyDiffResponse,
  RiskBudgetResponse,
  PresetsListResponse,
  ParamUpdate,
  ParamsBatchUpdate,
  CloneRequest,
  PresetSaveRequest,
} from "../types/strategy";

let _apiBase: Promise<string> | null = null;
function getApiBase(): Promise<string> {
  if (!_apiBase) {
    _apiBase = resolveBackendUrl();
  }
  return _apiBase;
}

async function req<T>(path: string, options?: RequestInit): Promise<T> {
  const base = await getApiBase();
  const res = await fetch(`${base}${path}`, {
    headers: { "Content-Type": "application/json" },
    ...options,
  });
  if (!res.ok) {
    throw new Error(`API ${path} returned ${res.status}`);
  }
  return res.json();
}

// ── Schema ────────────────────────────────────────────────────────────

export function fetchParamsSchema(): Promise<ParamsSchemaResponse> {
  return req<ParamsSchemaResponse>("/api/strategy/params-schema");
}

// ── Current params ────────────────────────────────────────────────────

export function fetchStrategyParams(
  strategyId: string,
): Promise<StrategyParamsResponse> {
  return req<StrategyParamsResponse>(
    `/api/strategy/params/${encodeURIComponent(strategyId)}`,
  );
}

// ── Validate ──────────────────────────────────────────────────────────

export function validateParams(
  strategyId: string,
  params: ParamUpdate[],
  changeNote = "",
): Promise<ParamsValidateResponse> {
  return req<ParamsValidateResponse>("/api/strategy/params/validate", {
    method: "POST",
    body: JSON.stringify({
      strategy_id: strategyId,
      params,
      change_note: changeNote,
    }),
  });
}

// ── Apply ─────────────────────────────────────────────────────────────

export function applyParams(
  strategyId: string,
  params: ParamUpdate[],
  changeNote = "",
  bypassPaperMode = false,
): Promise<ParamsApplyResponse> {
  const body: ParamsBatchUpdate = {
    strategy_id: strategyId,
    params,
    change_note: changeNote,
    bypass_paper_mode: bypassPaperMode,
  };
  return req<ParamsApplyResponse>("/api/strategy/params/apply", {
    method: "POST",
    body: JSON.stringify(body),
  });
}

// ── History ───────────────────────────────────────────────────────────

export function fetchStrategyHistory(
  strategyId: string,
): Promise<StrategyHistoryResponse> {
  return req<StrategyHistoryResponse>(
    `/api/strategy/history/${encodeURIComponent(strategyId)}`,
  );
}

// ── Compare ───────────────────────────────────────────────────────────

export function compareStrategies(
  a: string,
  b: string,
): Promise<StrategyDiffResponse> {
  return req<StrategyDiffResponse>(
    `/api/strategy/compare?strategy_id_a=${encodeURIComponent(a)}&strategy_id_b=${encodeURIComponent(b)}`,
  );
}

// ── Risk budget ───────────────────────────────────────────────────────

export function fetchRiskBudget(): Promise<RiskBudgetResponse> {
  return req<RiskBudgetResponse>("/api/strategy/risk-budget");
}

// ── Presets ───────────────────────────────────────────────────────────

export function fetchPresets(): Promise<PresetsListResponse> {
  return req<PresetsListResponse>("/api/strategy/presets");
}

export function savePreset(
  reqBody: PresetSaveRequest,
): Promise<{ success: boolean; message: string; preset_id: string }> {
  return req("/api/strategy/presets/save", {
    method: "POST",
    body: JSON.stringify(reqBody),
  });
}

export function applyPreset(
  presetId: string,
  targetStrategyId: string,
): Promise<{
  success: boolean;
  message: string;
  params_applied: number;
  error?: string;
}> {
  return req("/api/strategy/presets/apply", {
    method: "POST",
    body: JSON.stringify({
      preset_id: presetId,
      target_strategy_id: targetStrategyId,
    }),
  });
}

// ── Clone ─────────────────────────────────────────────────────────────

export function cloneStrategy(reqBody: CloneRequest): Promise<{
  success: boolean;
  message: string;
  strategy_id: string;
  version: string;
  error?: string;
}> {
  return req("/api/strategy/clone", {
    method: "POST",
    body: JSON.stringify(reqBody),
  });
}

// ── Toggle ────────────────────────────────────────────────────────────

export function toggleStrategy(
  strategyId: string,
  enabled: boolean,
): Promise<{
  success: boolean;
  strategy_id: string;
  enabled: boolean;
  error?: string;
}> {
  return req("/api/strategy/toggle", {
    method: "POST",
    body: JSON.stringify({ strategy_id: strategyId, enabled }),
  });
}

// ── Delete ────────────────────────────────────────────────────────────

export function deleteStrategy(
  strategyId: string,
): Promise<{ success: boolean; message: string; error?: string }> {
  return req("/api/strategy/delete", {
    method: "POST",
    body: JSON.stringify({ strategy_id: strategyId }),
  });
}
