// Read latest Discord messages from ag-gravity_control channel
const https = require('https');
const TOKEN = 'MTQ3OTY0ODcxNjA1MzgwNzI4NQ.GVMGbd.WN7BliH8oq9fqbaiQcyxXesJTYgBx-ObsDkK7o';
const CHANNEL_ID = '1483082084540223663';

function apiGet(path) {
  return new Promise((resolve, reject) => {
    const opts = {
      hostname: 'discord.com',
      path: `/api/v10${path}`,
      headers: { 'Authorization': `Bot ${TOKEN}` }
    };
    https.get(opts, res => {
      let data = '';
      res.on('data', c => data += c);
      res.on('end', () => {
        try { resolve(JSON.parse(data)); } catch { resolve(data); }
      });
    }).on('error', reject);
  });
}

async function main() {
  const limit = process.argv[2] || 15;
  const msgs = await apiGet(`/channels/${CHANNEL_ID}/messages?limit=${limit}`);
  if (!Array.isArray(msgs)) {
    console.log('Error:', JSON.stringify(msgs));
    return;
  }

  console.log(`=== #ag-gravity_control — Last ${msgs.length} messages ===\n`);

  msgs.reverse().forEach(m => {
    const time = new Date(m.timestamp).toLocaleString('ko-KR', { timeZone: 'Asia/Seoul', hour: '2-digit', minute: '2-digit', second: '2-digit' });
    const author = m.author?.username || '?';
    
    if (m.embeds?.length > 0) {
      m.embeds.forEach(e => {
        const title = e.title || '(no title)';
        const desc = (e.description || '').substring(0, 300);
        const colorHex = e.color ? `#${e.color.toString(16).padStart(6, '0')}` : 'default';
        const footer = e.footer?.text || '';
        console.log(`[${time}] 📦 EMBED [${colorHex}] ${title}`);
        if (desc) console.log(`  ${desc.replace(/\n/g, '\n  ')}`);
        if (footer) console.log(`  📎 ${footer}`);
      });
    } else if (m.content) {
      const content = m.content.substring(0, 300);
      console.log(`[${time}] 💬 ${author}: ${content}`);
    }
    console.log('');
  });
}

main().catch(e => console.error(e));
