import express from 'express';
import dotenv from 'dotenv';
import { login, fetchChannelMessages } from './bot.js';
import rssRouter from './rss.js';
import { initDatabase } from './database.js';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import fs from 'fs';

dotenv.config();

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// Ensure data directory exists
const dataDir = join(__dirname, '../data');
if (!fs.existsSync(dataDir)) {
  fs.mkdirSync(dataDir, { recursive: true });
}

// Initialize database
await initDatabase();

const app = express();
const PORT = process.env.PORT || 8000;

// Middleware
app.use(express.json());

// RSS routes
app.use('/rss', rssRouter);

// Health check
app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

// Parse channel IDs from environment variable
function getChannelIds() {
  const channelIdsStr = process.env.DISCORD_CHANNEL_IDS || process.env.DISCORD_CHANNEL_ID;
  if (!channelIdsStr) return [];
  return channelIdsStr.split(',').map(id => id.trim()).filter(id => id.length > 0);
}

// Fetch endpoint - trigger message fetch for a channel
app.post('/fetch/:channelId', async (req, res) => {
  try {
    const { channelId } = req.params;
    const limit = parseInt(req.query.limit, 10) || 100;

    const messages = await fetchChannelMessages(channelId, limit);

    res.json({
      success: true,
      messagesFetched: messages.length,
    });
  } catch (error) {
    console.error('Fetch error:', error);
    res.status(500).json({
      success: false,
      error: error.message,
    });
  }
});

// Fetch all configured channels
async function fetchAllChannels() {
  const channelIds = getChannelIds();
  const results = await Promise.allSettled(
    channelIds.map(id => fetchChannelMessages(id, 100))
  );

  let totalFetched = 0;
  results.forEach((result, index) => {
    if (result.status === 'fulfilled') {
      totalFetched += result.value.length;
      console.log(`  Channel ${channelIds[index]}: ${result.value.length} messages`);
    } else {
      console.error(`  Channel ${channelIds[index]}: failed - ${result.reason}`);
    }
  });

  console.log(`Total messages fetched: ${totalFetched}`);
}

async function start() {
  // Validate required environment variables
  const requiredEnv = ['DISCORD_TOKEN', 'DISCORD_CHANNEL_IDS'];
  const missing = requiredEnv.filter(env => !process.env[env]);

  if (missing.length > 0) {
    console.error(`Missing required environment variables: ${missing.join(', ')}`);
    console.error('Please copy .env.example to .env and fill in the values');
    process.exit(1);
  }

  // Login to Discord
  console.log('Logging in to Discord...');
  await login(process.env.DISCORD_TOKEN);

  // Initial fetch from all configured channels
  console.log('Fetching initial messages from all channels...');
  await fetchAllChannels();

  // Start HTTP server
  app.listen(PORT, '0.0.0.0', () => {
    console.log(`RSS server running on http://${process.env.BASE_URL}:${PORT}`);
    console.log(`RSS feed available at: http://${process.env.BASE_URL}:${PORT}/rss/`);
  });

  // Periodic fetch (every 5 minutes)
  const FETCH_INTERVAL = parseInt(process.env.FETCH_INTERVAL_MS, 10) || 5 * 60 * 1000;
  setInterval(async () => {
    try {
      await fetchAllChannels();
    } catch (error) {
      console.error('Periodic fetch failed:', error);
    }
  }, FETCH_INTERVAL);
}

start().catch((error) => {
  console.error('Failed to start:', error);
  process.exit(1);
});
