import { NextRequest, NextResponse } from 'next/server'
import * as fs from 'fs'
import * as path from 'path'

const commandFile = path.join(process.cwd(), 'task-history.json')

export async function GET(request: NextRequest) {
  try {
    let history = []
    
    if (fs.existsSync(commandFile)) {
      history = JSON.parse(fs.readFileSync(commandFile, 'utf-8'))
    }

    const { searchParams } = new URL(request.url)
    const project = searchParams.get('project')

    if (project && project !== 'all') {
      history = history.filter((h: any) => h.project === project)
    }

    return NextResponse.json({ history })
  } catch (error) {
    console.error('Error reading history:', error)
    return NextResponse.json({ history: [] })
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { task, command, project, action } = body

    let history = []
    if (fs.existsSync(commandFile)) {
      history = JSON.parse(fs.readFileSync(commandFile, 'utf-8'))
    }

    const entry = {
      id: Date.now().toString(),
      task,
      command,
      project: project || 'sitemente',
      reply: '',
      action: action || 'task',
      createdAt: new Date().toISOString(),
      status: 'pending',
      notified: false
    }

    history.push(entry)

    // Keep only last 50 entries
    if (history.length > 50) {
      history = history.slice(-50)
    }

    fs.writeFileSync(commandFile, JSON.stringify(history, null, 2))

    // Send Telegram notification to Horus
    try {
      const tgMessage = `📬 *New Task from MC*\n\n*Project:* ${project || 'sitemente'}\n*Task:* ${task}\n*Command:* ${command}\n\n_Reply via /api/command-reply/{id}_`
      
      // Use message tool to notify (will work if Telegram is configured)
      const { spawn } = require('child_process')
      spawn('curl', ['-s', '-X', 'POST', 
        'http://localhost:3000/api/messages/send',
        '-H', 'Content-Type: application/json',
        '-d', JSON.stringify({
          channel: 'telegram',
          target: '382315644',
          message: tgMessage
        })
      ], { detached: true, stdio: 'ignore' })
    } catch (e) {
      console.log('Telegram notification skipped')
    }

    return NextResponse.json({ success: true, entry })
  } catch (error) {
    console.error('Error saving history:', error)
    return NextResponse.json({ error: 'Failed to save' }, { status: 500 })
  }
}
