import sqlite3
import jieba
from collections import Counter
import numpy as np
from datetime import datetime
import os

def process_dates(dates=None):
    # 需要过滤的词语列表
    stop_words = ["...", "可能", "快訊",datetime.today().strftime('%Y'),datetime.today().strftime('%m')]

    # 预设日期为今天
    if dates is None:
        dates = [datetime.today().strftime('%Y%m%d')]  # 预设处理今天的日期

    # 连接到RSS数据库
    conn = sqlite3.connect('rss.db')
    cursor = conn.cursor()

    # 所有需要查询的新闻类别
    news_tables = ["社會新聞", "財經新聞", "運動新聞", "娛樂新聞", "旅遊新聞"]

    for today in dates:
        # 初始化计数器
        keyword_counter = Counter()

        # 查询指定日期的新闻并分词
        for table in news_tables:
            # 修正：在日期后加上 '%' 符号
            query = f'SELECT TITLE FROM "{table}" WHERE pubDate LIKE "{today[:4]}-{today[4:6]}-{today[6:]}%"'
            cursor.execute(query)
            titles = cursor.fetchall()

            # 分词并统计关键字出现次数
            for title_tuple in titles:
                title_text = title_tuple[0]
                words = jieba.cut(title_text)  # 分词
                # 过滤掉需要移除的词语
                filtered_words = [word for word in words if word not in stop_words]
                keyword_counter.update(filtered_words)

        # 如果没有取得任何标题，跳过当天的处理
        if not keyword_counter:
            print(f"{today} 没有找到任何新闻资料。")
            continue

        # 计算所有关键字的出现次数平均值和标准差
        counts = list(keyword_counter.values())
        mean_count = np.mean(counts)
        std_count = np.std(counts) if np.std(counts) != 0 else 1  # 避免标准差为 0

        # 计算每个关键字的 z-score
        z_scores = {keyword: (count - mean_count) / std_count for keyword, count in keyword_counter.items()}

        # 连接到 history.db 并创建结果数据表
        history_conn = sqlite3.connect('history.db')
        history_cursor = history_conn.cursor()

        # 每次重建数据表并覆盖
        history_cursor.execute(f'DROP TABLE IF EXISTS "{today}"')
        history_cursor.execute(f'''
            CREATE TABLE "{today}" (
                keyword TEXT,
                count INTEGER,
                z_score REAL
            )
        ''')

        # 插入符合条件的关键字及其 z-score
        for keyword, count in keyword_counter.items():
            if len(keyword) > 1 and abs(z_scores[keyword]) < 3 and count > 4:
                z_score = z_scores[keyword]
                history_cursor.execute(f'''
                    INSERT INTO "{today}" (keyword, count, z_score)
                    VALUES (?, ?, ?)
                ''', (keyword, count, z_score))

        history_conn.commit()

        # 查询所有符合条件的关键字
        history_cursor.execute(f'SELECT keyword FROM "{today}"')
        keywords = [row[0] for row in history_cursor.fetchall()]

        # 如果没有符合条件的关键字，跳过当天的后续处理
        if not keywords:
            print(f"{today} 没有符合条件的关键字。")
            history_conn.close()
            continue

        # 检查是否已经创建 _hot 数据表，如果没有则创建
        history_cursor.execute(f'''
            CREATE TABLE IF NOT EXISTS "{today}_hot" (
                source TEXT,     
                title TEXT,
                link TEXT UNIQUE
            )
        ''')

        # 查询原始数据库中的所有标题和链接，并检查标题是否包含任何关键字
        for table in news_tables:
            query = f'SELECT TITLE, LINK FROM "{table}" WHERE pubDate LIKE "{today[:4]}-{today[4:6]}-{today[6:]}%"'
            cursor.execute(query)
            rows = cursor.fetchall()

            for row in rows:
                source = f'{table}'
                title = row[0]
                link = row[1]
                if any(keyword in title for keyword in keywords):  # 如果标题包含任何关键字
                    # 检查该 link 是否已经存在，若不存在则插入
                    history_cursor.execute(f'''
                        SELECT 1 FROM "{today}_hot" WHERE link = ? LIMIT 1
                    ''', (link,))
                    if history_cursor.fetchone() is None:
                        history_cursor.execute(f'''
                            INSERT INTO "{today}_hot" (source, title, link)
                            VALUES (?, ?, ?)
                        ''', (source, title, link))

        history_conn.commit()
        history_conn.close()

    # 关闭原始数据库连接
    conn.close()

    # 确认 history.db 是否存在，并输出所在路径
    if os.path.exists('history.db'):
        print(f"符合条件的标题和链接已保存到 history.db 数据表，文件位置：{os.path.abspath('history.db')}")
    else:
        print("未找到 history.db，请确认程序是否正常执行，或检查是否有异常发生。")

# 示例：处理今天的数据
process_dates()


# 範例：處理指定日期的資料（如 20231101 和 20231102）
#process_dates(["20241102", "20241105", "20241111", "20241112", "20241116", "20241117", "20241118", "20241119"])