const logger = require('consola');
const { getMetaWithUrl } = require('../service/media_fetcher');
const { matchUrlFromStr } = require('../utils/regex');
const { getSongInfo, buildSongUrl } = require('../service/music_platform/tunehub');

function parseTunehubParams(url) {
    try {
        const parsed = new URL(url);
        if (!parsed.hostname.includes('music-dl.sayqz.com')) {
            return null;
        }
        const source = parsed.searchParams.get('source');
        const id = parsed.searchParams.get('id');
        if (!source || !id) {
            return null;
        }
        return { source, id };
    } catch (err) {
        return null;
    }
}

function parsePageUrlParams(url) {
    if (!url) {
        return null;
    }
    if (url.indexOf('music.163.com') >= 0 || url.indexOf('m.music.163.com') >= 0) {
        const match = url.match(/id=(\d+)/);
        if (match && match[1]) {
            return { source: 'netease', id: match[1] };
        }
    }
    if (url.indexOf('y.qq.com') >= 0) {
        const match = url.match(/songDetail\/([A-Za-z0-9]+)/);
        if (match && match[1]) {
            return { source: 'qq', id: match[1] };
        }
    }
    return null;
}

function buildSongMetaFromTunehub(source, info, pageUrl, songId) {
    return {
        songName: info.name || '',
        artist: info.artist || '',
        album: info.album || '',
        duration: 0,
        coverUrl: info.pic || '',
        pageUrl,
        audios: [
            {
                url: info.url || buildSongUrl(source, songId),
            }
        ],
        fromMusicPlatform: true,
        resourceForbidden: false,
        source,
    };
}

async function getMeta(req, res) {
    const query = req.query;

    const url = matchUrlFromStr(query.url);

    if (!url) {
        res.send({
            status: 1,
            message: "url is invalid",
        });
        return;
    }

    let songMeta = null;
    const params = parseTunehubParams(url) || parsePageUrlParams(url);
    if (params) {
        const tunehubInfo = await getSongInfo(params.source, params.id);
        if (tunehubInfo) {
            songMeta = buildSongMetaFromTunehub(params.source, tunehubInfo, url, params.id);
        }
    }
    if (!songMeta) {
        songMeta = await getMetaWithUrl(url);
        songMeta && (songMeta.pageUrl = url);
    }

    res.send({
        status: songMeta ? 0 : 1,
        data: {
            songMeta,
        }
    });
}

module.exports = {
    getMeta: getMeta
}
