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

const AGENT_SECRET = process.env.AGENT_SECRET || 'agent-mc-secret-2026';

export async function POST(request: Request) {
  // Check for agent authorization
  const authHeader = request.headers.get('authorization');
  if (authHeader !== `Bearer ${AGENT_SECRET}`) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }
  
  try {
    const body = await request.json();
    const { agent, time, content, tags } = body;

    if (!agent || !content) {
      return NextResponse.json({ error: 'Missing agent or content' }, { status: 400 });
    }

    // Get today's date
    const today = new Date().toISOString().split('T')[0];
    const memoryDir = '/root/.openclaw/workspace/memory';
    const filePath = path.join(memoryDir, `${today}.md`);

    // Build entry
    const tagsStr = tags && tags.length > 0 
      ? `\n[Tags: ${tags.map((t: string) => '#' + t).join(', ')}]` 
      : '';
    const entry = `\n\n## ${agent} - ${time || new Date().toTimeString().slice(0,5)}\n${tagsStr}\n${content}`;

    // Append to file
    if (fs.existsSync(filePath)) {
      fs.appendFileSync(filePath, entry, 'utf8');
    } else {
      // Create new file with header
      const header = `# Daily Memory - ${today}\n`;
      fs.writeFileSync(filePath, header + entry, 'utf8');
    }

    return NextResponse.json({ success: true, date: today, entry: entry.trim() });
  } catch (error) {
    console.error('Memory append error:', error);
    return NextResponse.json({ error: 'Failed to append memory' }, { status: 500 });
  }
}
