import fs from 'fs';
import { promises as fsp } from 'fs';
import path from 'path';
import { Router, Request, Response } from 'express';
import { config } from '../config';
import { probeVideo, getVideoCodec, getVideoDuration, getVideoFps } from '../services/ffmpeg';
import type { VideoMeta } from '@abcvideo/shared';

const router = Router();

// GET /api/videos
router.get('/', async (_req: Request, res: Response) => {
  try {
    const files = await fsp.readdir(config.videosDir, { withFileTypes: true });
    const videos = files
      .filter(f => f.isFile() && /\.(mp4|mkv|webm|mov|avi)$/i.test(f.name))
      .map(f => ({ videoId: f.name, filename: f.name }));
    res.json(videos);
  } catch {
    res.json([]);
  }
});

// GET /api/meta/:videoId
router.get('/:videoId', async (req: Request, res: Response) => {
  const { videoId } = req.params;
  const filePath = path.resolve(config.videosDir, videoId);
  if (!filePath.startsWith(path.resolve(config.videosDir))) {
    res.status(400).json({ error: 'Invalid video ID' });
    return;
  }
  if (!fs.existsSync(filePath)) {
    res.status(404).json({ error: 'Video not found' });
    return;
  }
  try {
    const probe = await probeVideo(filePath);
    const videoStream = probe.streams.find(s => s.codec_type === 'video');
    const stat = await fsp.stat(filePath);
    const meta: VideoMeta = {
      videoId,
      filename: videoId,
      size: stat.size,
      duration: getVideoDuration(probe),
      fps: getVideoFps(probe),
      width: videoStream?.width || 0,
      height: videoStream?.height || 0,
      codec: getVideoCodec(probe),
      hlsStatus: 'idle',
      createdAt: stat.birthtime.toISOString(),
    };
    res.json(meta);
  } catch (err) {
    res.status(500).json({ error: 'Metadata extraction failed', detail: String(err) });
  }
});

// DELETE /api/videos/:videoId
router.delete('/:videoId', async (req: Request, res: Response) => {
  const { videoId } = req.params;
  const filePath = path.resolve(config.videosDir, videoId);
  if (!filePath.startsWith(path.resolve(config.videosDir))) {
    res.status(400).json({ error: 'Invalid video ID' });
    return;
  }
  try {
    await fsp.unlink(filePath);
    // Remove HLS dir
    const hlsId = videoId.replace(/\.[^.]+$/, '');
    await fsp.rm(path.join(config.hlsDir, hlsId), { recursive: true, force: true });
    res.json({ success: true });
  } catch {
    res.status(500).json({ error: 'Delete failed' });
  }
});

export default router;
