const express = require('express');
const cors = require('cors');
const { createProxyMiddleware } = require('http-proxy-middleware');
const fetch = require('node-fetch');
const path = require('path');
const fs = require('fs');

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

// 中间件
app.use(cors());
app.use(express.json());

// 静态文件服务
app.use(express.static(path.join(__dirname, '../public')));

// 健康检查
app.get('/health', (req, res) => {
  res.json({ status: 'ok', time: new Date().toISOString() });
});

// 获取频道列表
app.get('/api/channels', async (req, res) => {
  try {
    const dataDir = path.join(__dirname, '../../ui/dist-web/api');
    const filePath = path.join(dataDir, 'result.txt');
    
    if (fs.existsSync(filePath)) {
      const content = fs.readFileSync(filePath, 'utf-8');
      res.setHeader('Content-Type', 'text/plain; charset=utf-8');
      res.send(content);
    } else {
      res.status(404).json({ error: 'Channel data not found' });
    }
  } catch (error) {
    console.error('Error reading channels:', error);
    res.status(500).json({ error: error.message });
  }
});

// 代理 M3U8 流（解决跨域）
app.get('/proxy/m3u8', async (req, res) => {
  const { url } = req.query;
  
  if (!url) {
    return res.status(400).json({ error: 'Missing url parameter' });
  }

  try {
    console.log(`[Proxy] M3U8: ${url}`);
    
    const response = await fetch(url, {
      headers: {
        'User-Agent': req.headers['user-agent'] || 'Mozilla/5.0',
        'Referer': new URL(url).origin
      },
      timeout: 10000
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }

    const content = await response.text();
    
    // 转换相对路径为绝对路径
    const baseUrl = url.substring(0, url.lastIndexOf('/') + 1);
    const modifiedContent = content.replace(
      /^(?!#)([^\s].*\.ts.*)$/gm,
      (match) => {
        if (match.startsWith('http')) return match;
        return `/proxy/ts?url=${encodeURIComponent(baseUrl + match)}`;
      }
    );

    res.setHeader('Content-Type', 'application/vnd.apple.mpegurl');
    res.setHeader('Cache-Control', 'no-cache');
    res.send(modifiedContent);
    
  } catch (error) {
    console.error('[Proxy] Error:', error.message);
    res.status(500).json({ error: error.message });
  }
});

// 代理 TS 流
app.get('/proxy/ts', async (req, res) => {
  const { url } = req.query;
  
  if (!url) {
    return res.status(400).json({ error: 'Missing url parameter' });
  }

  try {
    const response = await fetch(url, {
      headers: {
        'User-Agent': req.headers['user-agent'] || 'Mozilla/5.0'
      }
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }

    response.headers.forEach((value, name) => {
      res.setHeader(name, value);
    });

    response.body.pipe(res);
    
  } catch (error) {
    console.error('[Proxy] TS Error:', error.message);
    res.status(500).json({ error: error.message });
  }
});

// 通用代理（用于其他类型的流）
app.get('/proxy/stream', async (req, res) => {
  const { url } = req.query;
  
  if (!url) {
    return res.status(400).json({ error: 'Missing url parameter' });
  }

  try {
    console.log(`[Proxy] Stream: ${url}`);
    
    const response = await fetch(url, {
      headers: {
        'User-Agent': req.headers['user-agent'] || 'Mozilla/5.0'
      }
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }

    response.headers.forEach((value, name) => {
      res.setHeader(name, value);
    });

    response.body.pipe(res);
    
  } catch (error) {
    console.error('[Proxy] Stream Error:', error.message);
    res.status(500).json({ error: error.message });
  }
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`🚀 IPTV Web Server running on port ${PORT}`);
  console.log(`📺 Access: http://localhost:${PORT}`);
});
