import { NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'

export const dynamic = 'force-dynamic'

// Get all Hookd items
export async function GET(request: Request) {
  const url = new URL(request.url)
  const action = url.searchParams.get('action') || 'list'
  
  try {
    const possiblePaths = [
      path.join(process.cwd(), '..', 'chrome-extensions', 'hookd', 'data.json'),
      '/var/www/hostpioneers.com/public_html/contacts.json',
    ]
    
    let data: any[] = []
    
    // Try to read from Hookd storage
    for (const filePath of possiblePaths) {
      if (fs.existsSync(filePath)) {
        const content = fs.readFileSync(filePath, 'utf-8')
        data = JSON.parse(content)
        break
      }
    }
    
    if (action === 'stats') {
      return NextResponse.json({
        total: data.length,
        byCategory: data.reduce((acc: any, item) => {
          const cat = item.category || 'Uncategorized'
          acc[cat] = (acc[cat] || 0) + 1
          return acc
        }, {}),
        aiProcessed: data.filter((i: any) => i.aiProcessed).length,
        saved: data.filter((i: any) => i.saved).length,
        recent: data.slice(0, 10)
      })
    }
    
    return NextResponse.json({ items: data })
  } catch (error) {
    console.error('Hookd API error:', error)
    return NextResponse.json({ items: [], error: 'Failed to fetch' }, { status: 200 })
  }
}

// Process items with AI
export async function POST(request: Request) {
  try {
    const body = await request.json()
    const { items, instruction } = body
    
    // This would call MiniMax API to process items
    // For now, return mock AI analysis
    
    const results = items.map((item: any) => ({
      id: item.id,
      category: guessCategory(item),
      score: guessScore(item),
      tags: guessTags(item),
      summary: item.content?.slice(0, 100) + '...'
    }))
    
    return NextResponse.json({ results })
  } catch (error) {
    console.error('AI processing error:', error)
    return NextResponse.json({ error: 'Processing failed' }, { status: 500 })
  }
}

function guessCategory(item: any): string {
  const content = (item.content || '').toLowerCase()
  const link = (item.link || '').toLowerCase()
  
  if (content.includes('ai') || content.includes('gpt') || content.includes('claude') || 
      content.includes('openai') || content.includes('anthropic') || 
      link.includes('github.com') || link.includes('huggingface')) {
    return 'AI'
  }
  if (content.includes('news') || content.includes('breaking') || content.includes('just in')) {
    return 'News'
  }
  if (content.includes('idea') || content.includes('thought') || content.includes('what if')) {
    return 'Ideas'
  }
  if (content.includes('lol') || content.includes('meme') || content.includes('funny') || content.includes('😂')) {
    return 'Memes'
  }
  return 'Other'
}

function guessScore(item: any): number {
  const content = (item.content || '').toLowerCase()
  let score = 5
  
  if (item.link) score += 1
  if (content.length > 100) score += 1
  if (content.includes('github')) score += 1
  if (content.includes('ai') || content.includes('gpt')) score += 2
  
  return Math.min(10, score)
}

function guessTags(item: any): string[] {
  const tags: string[] = []
  const content = (item.content || '').toLowerCase()
  
  if (content.includes('ai')) tags.push('AI')
  if (content.includes('tool')) tags.push('Tools')
  if (content.includes('news')) tags.push('News')
  if (content.includes('tutorial')) tags.push('Tutorial')
  if (content.includes('github')) tags.push('Code')
  
  return tags
}
