// Rigo Backend API Client
// Backend URL: http://3.129.218.141:8000

const RIGO_API_BASE = "http://3.129.218.141:8000";

export interface AnalysisResult {
  pattern: string;
  apex: string;
  cobb_angle: number;
  thoracic_convexity?: string;
  lumbar_cobb_deg?: number;
  l4_tilt_deg?: number;
  l5_tilt_deg?: number;
  pelvic_tilt: string;
}

export interface BraceParameters {
  pressure_pad_level: string;
  pressure_pad_depth: string;
  expansion_window_side: string;
  lumbar_support: boolean;
  include_shell: boolean;
}

export interface AnalysisResponse {
  success: boolean;
  analysis: AnalysisResult;
  brace_params: BraceParameters;
  model_url: string | null;
}

export interface RegenerateRequest {
  pressure_pad_level: string;
  pressure_pad_depth: string;
  expansion_window_side: string;
  lumbar_support: boolean;
  include_shell: boolean;
}

export const rigoApi = {
  /**
   * Check backend health
   */
  health: async (): Promise<{ status: string; service: string }> => {
    const res = await fetch(`${RIGO_API_BASE}/api/health`);
    if (!res.ok) throw new Error(`Health check failed: ${res.status}`);
    return res.json();
  },

  /**
   * Analyze X-ray image and generate brace model
   */
  analyze: async (imageFile: File): Promise<AnalysisResponse> => {
    const formData = new FormData();
    formData.append("image", imageFile);

    const res = await fetch(`${RIGO_API_BASE}/api/analyze`, {
      method: "POST",
      body: formData,
    });

    if (!res.ok) {
      const text = await res.text().catch(() => "");
      throw new Error(`Analysis failed: ${res.status} ${text}`);
    }

    return res.json();
  },

  /**
   * Regenerate brace with different parameters
   */
  regenerate: async (params: RegenerateRequest): Promise<{ success: boolean; model_url: string }> => {
    const res = await fetch(`${RIGO_API_BASE}/api/regenerate`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(params),
    });

    if (!res.ok) {
      const error = await res.json().catch(() => ({ detail: "Unknown error" }));
      throw new Error(error.detail || "Regeneration failed");
    }

    return res.json();
  },

  /**
   * Get full URL for a model file
   */
  getModelUrl: (filename: string): string => {
    return `${RIGO_API_BASE}/api/models/${filename}`;
  },

  /**
   * Get the base URL (for constructing model URLs from relative paths)
   */
  getBaseUrl: (): string => {
    return RIGO_API_BASE;
  },
};
