import { NextRequest, NextResponse } from 'next/server'

// MiniMax API call for report generation
async function callMiniMax(prompt: string) {
  const response = await fetch('https://api.minimax.chat/v1/text/chatcompletion_pro', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${process.env.MINIMAX_API_KEY}`
    },
    body: JSON.stringify({
      model: 'abab6.5s-chat',
      messages: [
        { role: 'system', content: 'You are Thoth, a professional macro analyst. Generate HTML reports.' },
        { role: 'user', content: prompt }
      ]
    })
  })
  
  const data = await response.json()
  return data.choices?.[0]?.message?.content || ''
}

export async function POST(request: NextRequest) {
  try {
    const { type, date } = await request.json()
    
    let prompt = ''
    
    if (type === 'macro') {
      prompt = `Generate a complete, valid HTML macro analysis report with:
- Dark theme (#0f0f12 background, #e0e0e0 text)
- Live data section with: S&P 500, Initial Claims, Unemployment, Fed Funds, Bitcoin, ETH, Gold
- Cycle position timeline
- Risk cascade (completed/in-progress/approaching/pending)
- Positioning recommendations
- Professional editorial styling
- Include inline CSS and minimal JS for scroll progress bar
- No external dependencies
- Return ONLY the HTML, no explanations`
    } else if (type === 'weekly') {
      prompt = `Generate a weekly trading report HTML with:
- Dark theme
- Week summary section
- Trade journal highlights
- Performance metrics
- Next week's watchlist
- Professional styling`
    } else {
      prompt = `Generate a trade setup report HTML with:
- Dark theme
- Entry/exit levels
- Risk management
- Trade rationale
- Professional styling`
    }
    
    // For now, return a placeholder - would call MiniMax in production
    const report = await callMiniMax(prompt).catch(() => '')
    
    // If no LLM response, return template
    if (!report) {
      return NextResponse.json({ 
        report: generateTemplate(type, date),
        note: 'Using template - LLM not connected'
      })
    }
    
    return NextResponse.json({ report })
    
  } catch (error) {
    console.error('Report generation error:', error)
    return NextResponse.json({ error: 'Failed to generate' }, { status: 500 })
  }
}

function generateTemplate(type: string, date: string) {
  return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Thoth Trading Report - ${date}</title>
<style>
body { background: #0f0f12; color: #e0e0e0; font-family: system-ui; padding: 40px; }
h1 { background: linear-gradient(90deg, #667eea, #ff69b4); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
.metric { background: #1e1e24; padding: 20px; border-radius: 10px; margin: 10px 0; }
</style>
</head>
<body>
<h1>Thoth Trading Report</h1>
<p>Date: ${date}</p>
<p>Type: ${type}</p>
<div class="metric"><strong>Coming soon...</strong></div>
</body>
</html>`
}
