import { Router } from 'express';
import axios from 'axios';
import * as cheerio from 'cheerio';
import { z } from 'zod';

const router = Router();

const previewSchema = z.object({
    url: z.string().min(1)
});

router.post('/meta-preview', async (req, res) => {
    try {
        let { url } = previewSchema.parse(req.body);

        // Add protocol if missing
        if (!url.startsWith('http://') && !url.startsWith('https://')) {
            url = `https://${url}`;
        }

        const response = await axios.get(url, {
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
                'Accept-Language': 'en-US,en;q=0.9',
                'Accept-Encoding': 'gzip, deflate, br',
                'Upgrade-Insecure-Requests': '1',
                'Sec-Fetch-Dest': 'document',
                'Sec-Fetch-Mode': 'navigate',
                'Sec-Fetch-Site': 'none',
                'Sec-Fetch-User': '?1',
                'Cache-Control': 'max-age=0'
            },
            timeout: 30000,
            httpAgent: new (require('http').Agent)({ family: 4, keepAlive: true }),
            httpsAgent: new (require('https').Agent)({ family: 4, rejectUnauthorized: false, keepAlive: true }),
            validateStatus: (status) => status < 500
        });

        const html = response.data;
        const $ = cheerio.load(html);

        const title = $('title').text() || $('meta[property="og:title"]').attr('content') || '';
        const description = $('meta[name="description"]').attr('content') || $('meta[property="og:description"]').attr('content') || '';

        // Attempt to find favicon
        let favicon = '';
        const linkIcon = $('link[rel="icon"], link[rel="shortcut icon"], link[rel="apple-touch-icon"]').attr('href');
        if (linkIcon) {
            if (linkIcon.startsWith('http')) {
                favicon = linkIcon;
            } else if (linkIcon.startsWith('//')) {
                favicon = `https:${linkIcon}`;
            } else {
                const urlObj = new URL(url);
                favicon = `${urlObj.protocol}//${urlObj.host}${linkIcon.startsWith('/') ? '' : '/'}${linkIcon}`;
            }
        } else {
            const urlObj = new URL(url);
            favicon = `${urlObj.protocol}//${urlObj.host}/favicon.ico`;
        }

        res.json({
            title: title.trim(),
            description: description.trim(),
            favicon,
            url: url
        });

    } catch (error) {
        console.error('Meta preview error:', error);
        if (error instanceof z.ZodError) {
            return res.status(400).json({ error: 'Invalid URL provided' });
        }
        res.status(500).json({ error: 'Failed to fetch page metadata' });
    }
});

export const toolsRouter = router;
