/* ============ Claude API Integration ============ */

const CLAUDE_CONFIG = {
  model: 'claude-sonnet-4-6',
  proxyUrl: '/api/claude', // server-side proxy avoids CORS
};

async function claudeAPICall(messages, systemPrompt = '', temperature = 1) {
  const apiKey = getApiKey('claude');
  if (!apiKey) {
    return { ok: false, error: 'Claude API key not configured. Add it in Settings → API Keys.' };
  }

  try {
    const payload = {
      model: CLAUDE_CONFIG.model,
      max_tokens: 2048,
      messages: messages,
    };
    if (systemPrompt) payload.system = systemPrompt;

    const response = await withTimeout(
      fetch(CLAUDE_CONFIG.proxyUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'x-claude-key': apiKey,
        },
        body: JSON.stringify(payload),
      }),
      20000
    );

    if (!response.ok) {
      const errorData = await response.json();
      return { ok: false, error: errorData.error?.message || `API error: ${response.status}` };
    }

    const data = await response.json();
    if (data.content && data.content.length > 0) {
      return { ok: true, text: data.content[0].text, usage: data.usage };
    }
    return { ok: false, error: 'No response from Claude' };
  } catch (e) {
    return { ok: false, error: e.message };
  }
}

async function claudeComplete(prompt) {
  const messages = [{ role: 'user', content: prompt }];
  const result = await claudeAPICall(messages);
  if (result.ok) return result.text;
  throw new Error(result.error);
}

async function claudeDealAnalysis(dealSummary) {
  const systemPrompt = `You are an expert real estate fix-and-flip underwriter. Analyze deals based on profit margin, ROI, the 70% rule, rehab-to-ARV ratio, and risk factors.`;
  const prompt = `${dealSummary}\n\nScore this deal from 1 (terrible) to 10 (excellent). Respond ONLY with minified JSON:\n{"score": <1-10>, "verdict": "<3-5 words>", "summary": "<one sentence>", "strengths": ["<point>", "<point>"], "risks": ["<point>", "<point>"], "reasoning": "<2 sentences>"}`;

  const messages = [{ role: 'user', content: prompt }];
  const result = await claudeAPICall(messages, systemPrompt, 0.7);
  if (result.ok) {
    try {
      const match = (result.text || '').match(/\{[\s\S]*\}/);
      if (!match) throw new Error('No JSON found');
      return { ok: true, analysis: JSON.parse(match[0]) };
    } catch (e) {
      return { ok: false, error: 'Could not parse Claude response: ' + e.message };
    }
  }
  return { ok: false, error: result.error };
}

async function claudePropertyAnalysis(propertyData) {
  const systemPrompt = `You are a real estate market analyst. Provide insight on property value, rental potential, and market conditions.`;
  const prompt = `Analyze this property data and provide market insights:\n${JSON.stringify(propertyData, null, 2)}\n\nRespond with JSON: {"marketValue": "<analysis>", "rentalPotential": "<analysis>", "riskFactors": ["<risk>"], "recommendations": ["<rec>"]}`;

  const messages = [{ role: 'user', content: prompt }];
  const result = await claudeAPICall(messages, systemPrompt, 0.7);
  if (result.ok) {
    try {
      const match = (result.text || '').match(/\{[\s\S]*\}/);
      if (!match) throw new Error('No JSON found');
      return { ok: true, analysis: JSON.parse(match[0]) };
    } catch (e) {
      return { ok: false, error: 'Parse error' };
    }
  }
  return { ok: false, error: result.error };
}

/* ---- Initialize window.claude ---- */
window.claude = {
  complete: claudeComplete,
  dealAnalysis: claudeDealAnalysis,
  propertyAnalysis: claudePropertyAnalysis,
  apiCall: claudeAPICall,
};

Object.assign(window, { claudeComplete, claudeDealAnalysis, claudePropertyAnalysis, CLAUDE_CONFIG });
