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 || 3000;

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

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

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

// 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,
    });
  }
});

async function start() {
  // Validate required environment variables
  const requiredEnv = ['DISCORD_TOKEN', 'DISCORD_CHANNEL_ID'];
  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
  console.log('Fetching initial messages...');
  await fetchChannelMessages(process.env.DISCORD_CHANNEL_ID, 100);

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

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

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