import asyncio
import aiosqlite
import requests
import datetime
from bs4 import BeautifulSoup
from playwright.async_api import async_playwright

async def fetch_content(url, use_js=False):
    """
    獲取頁面內容，根據需要選擇是否使用 Pyppeteer 來渲染 JavaScript。

    Args:
        url (str): 目標頁面的 URL。
        use_js (bool): 是否使用 use_js 來渲染頁面。

    Returns:
        str: 獲取到的 HTML 內容。
    """
    if not use_js:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                          'AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/112.0.0.0 Safari/537.36'
        }
        try:
            response = requests.get(url, headers=headers)
            response.raise_for_status()
            return response.text
        except requests.RequestException as e:
            print(f"Failed to fetch data from {url} using requests: {e}")
            return None
    else:
        try:
            async with async_playwright() as p:
                browser = await p.chromium.launch(headless=True)
                page = await browser.new_page()
                await page.goto(url)
                await page.wait_for_load_state("networkidle")
                #await asyncio.sleep(1)  # 等待頁面完全加載
                content = await page.content()
                await browser.close()
                return content
        except Exception as e:
            print(f"Failed to fetch data from {url} using Pyppeteer: {e}")
            return None


def collect_tags_from_html(html, source, text_selector, link_selector, skip_words=None):
    #print(html)
    """
    從 HTML 內容中提取標籤並返回列表。

    Args:
        html (str): HTML 內容。
        source (str): 資源的名稱。
        text_selector (str): 用於找到標籤文字的 CSS 選擇器。
        link_selector (str): 用於找到 URL 的 CSS 選擇器。
        skip_words (list, optional): 要忽略的詞。

    Returns:
        list: 包含 (source, tag, url) 的元組列表。
    """
    tags = []
    try:
        # 判斷是否為 RSS 格式
        if '<html ' in html.lower():
            soup = BeautifulSoup(html, 'html.parser')
            #print("<html>")
        else:
            soup = BeautifulSoup(html, 'xml')
            #print("<xml>")

        text_elements = soup.select(text_selector)
        link_elements = soup.select(link_selector)

        # 除錯輸出
        print(f"Source: {source}")
        print(f"Number of text elements: {len(text_elements)}")
        print(f"Number of link elements: {len(link_elements)}")

        if len(text_elements) != len(link_elements):
            print(f"Warning: The number of text elements and link elements do not match for source '{source}'.")

        for text_elem, link_elem in zip(text_elements, link_elements):
            text = text_elem.get_text(strip=True)
            link = link_elem.get('href', link_elem.get_text(strip=True)).strip()
            pubDate = datetime.datetime.now()

            # 跳過包含忽略詞的標籤
            if skip_words and any(word in text for word in skip_words):
                continue

            tags.append((source, text, link, pubDate))
    except Exception as e:
        print(f"Error parsing HTML from {source}: {e}")

    return tags

async def insert_tags_async(db, tags):
    """
    使用異步方式將標籤資料插入到 SQLite 資料庫中。

    Args:
        db (aiosqlite.Connection): SQLite 資料庫的連接。
        tags (list): 包含 (source, tag, url, pubDate) 的元組列表。
    """
    if not tags:
        return
    try:
        await db.executemany("INSERT INTO Tags (source, tag, url, pubDate) VALUES (?, ?, ?, ?)", tags)
        await db.commit()
        print(f"Inserted {len(tags)} tags into the database.")
    except Exception as e:
        print(f"Error inserting data into SQLite: {e}")


async def process_source_async(source, db):
    """
    處理單個資料來源，抓取並插入標籤資料。

    Args:
        source (dict): 資料來源的設定。
        db (aiosqlite.Connection): SQLite 資料庫的連接。
    """
    print(f"Processing source: {source['source']}")
    html = await fetch_content(source["url"], use_js=source.get("use_js", False))
    if html:
        tags = collect_tags_from_html(
            html,
            source["source"],
            source["text_selector"],
            source["link_selector"],
            skip_words=source.get("skip_words")
        )
        if tags:
            await insert_tags_async(db, tags)
        else:
            print(f"No tags found for source '{source['source']}'.")
    else:
        print(f"Failed to retrieve HTML content for {source['source']}")


async def main():
    # 初始化異步 SQLite 資料庫
    async with aiosqlite.connect('tag.db') as db:
        await db.execute('''
            CREATE TABLE IF NOT EXISTS Tags (
                source TEXT,
                tag TEXT,
                url TEXT,
                pubDate DATETIME
            )
        ''')
        await db.commit()

        # 各來源的收集設置
        sources = [
            {
                "url": "https://udn.com/news/index",
                "source": "聯合新聞網",
                "text_selector": "a.btn-keyword",
                "link_selector": "a.btn-keyword",
                "use_js": True,  # 使用js渲染頁面
                "skip_words": ["股市行情"]
            },
            {
                "url": "https://www.ltn.com.tw/",
                "source": "自由時報",
                "text_selector": "#hot_keyword_area span a",
                "link_selector": "#hot_keyword_area span a",
                "use_js": True,  # 使用js渲染頁面
                "skip_words": None
            },
            {
                "url": "https://www.ettoday.net/news/hot-tag.htm",
                "source": "ETtoday新聞雲",
                "text_selector": ".menu_txt_2 a",
                "link_selector": ".menu_txt_2 a",
                "use_js": False,
                "skip_words": None
            },
            {
                "url": "https://trends.google.com/trending/rss?geo=TW&hours=1",
                "source": "Google Trends",
                "text_selector": "item title",
                "link_selector": "item link",
                "use_js": False,
                "skip_words": None
            },
            {
                "url": "https://tw.search.yahoo.com/search?p=熱門搜尋",
                "source": "Yahoo",
                "text_selector": "a.keyword-text",
                "link_selector": "a.keyword-text",
                "use_js": False,
                "skip_words": None
            }
        ]

        # 建立任務列表
        tasks = [process_source_async(source, db) for source in sources]

        # 同時運行所有任務
        await asyncio.gather(*tasks)

    print("標籤收集完成，數據已儲存在 SQLite 資料庫中。")


if __name__ == "__main__":
    asyncio.run(main())

