import requests
import sqlite3
import feedparser
from datetime import datetime
import re
import time

# 配置部分
DATABASE_NAME = 'bbs.db'

BBS_LIST = [
    "Gossiping", "PttHot", "FW", "PTT", "NEWS", "dinos", "Beauty",
    "Food", "Stupid", "Tech_Job", "beauty-skin", "Boy-Girl",
    "WomenTalk", "marriage", "KoreaDrama", "ACG", "Movie",
    "graynoah", "Car", "AllTogether", "BabyMother", "BuyTogether",
    "PC_Shopping", "e-shopping", "Hate", "Joke", "Wanted",
    "CPLife", "MobileComm", "NBA", "Baseball", "Stock",
    "Taipei", "NewTaipeiCity", "Taoyuan", "Tainan",
    "Taichung", "Kaohsiung"
]

def sanitize_table_name(name):
    """移除或替換資料表名稱中的特殊字元，確保SQL安全"""
    return re.sub(r'[^A-Za-z0-9_]', '_', name)

def create_database():
    """建立SQLite資料庫和每個看板的表格"""
    conn = sqlite3.connect(DATABASE_NAME)
    cursor = conn.cursor()
    for bbs in BBS_LIST:
        table_name = sanitize_table_name(bbs)
        cursor.execute(f'''
            CREATE TABLE IF NOT EXISTS "{table_name}" (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                source TEXT,
                author TEXT,
                title TEXT,
                link TEXT UNIQUE,
                pubDate TEXT,
                description TEXT,
                xpush INTEGER,
                xshit INTEGER
            )
        ''')
    conn.commit()
    conn.close()

def fetch_rss_feed(rss_url):
    """使用 feedparser 抓取並解析 RSS 資料"""
    try:
        response = requests.get(rss_url, timeout=10)
        response.raise_for_status()

        # 將內容解碼為字符串，並將無效字節替換為替換字符（�）
        content = response.content.decode('utf-8', errors='replace')

        # 使用正則表達式將所有不可見字符和無效字符替換為空白
        # 包括控制字符、DEL 字符、NO-BREAK SPACE 以及 0xFFFE 和 0xFFFF
        content = re.sub(r'[\x00-\x1F\x7F\u00A0\uFFFE\uFFFF]', ' ', content)

        # 解析解碼後的內容
        feed = feedparser.parse(content)
        if feed.bozo:
            print(f"解析 RSS 失敗: {rss_url} - {feed.bozo_exception}")
            return None
        return feed
    except requests.RequestException as e:
        print(f"請求異常: {rss_url} - {e}")
        return None

def parse_and_store(feed, table_name, conn, cursor):
    """解析 RSS 資料並存入 SQLite 的指定表格"""
    for entry in feed.entries:
        title = entry.get('title', '').strip()
        link = entry.get('link', '').strip()
        pub_date = entry.get('published', '').strip() if 'published' in entry else ''
        description = entry.get('description', '').strip()
        author = entry.get('author', '').strip() if 'author' in entry else '未知'
        if 'content' in entry:
            content = entry.content[0].value.strip()

        # 移除 <pre></pre> 標籤
        description = re.sub(r'</?pre>', '', description)

        # 轉換日期格式為 YYYY-MM-DD
        try:
            # 使用 fromisoformat 解析 ISO 8601 格式
            date_obj = datetime.fromisoformat(pub_date)
            date_str = date_obj.strftime('%Y-%m-%d')
        except (ValueError, TypeError):
            date_str = ''

        # 計算 xpush 和 xshit
        xpush = len(re.findall(r'推', content))
        xshit = len(re.findall(r'噓', content))

        # 插入資料
        try:
            cursor.execute(f'''
                INSERT OR IGNORE INTO "{table_name}" (
                    source, author, title, link, pubDate, description, xpush, xshit
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ''', (table_name, author, title, link, date_str, description, xpush, xshit))
            conn.commit()
            print(f"插入資料: {title} 到表 {table_name}")
        except sqlite3.IntegrityError:
            print(f"重複資料略過: {title} 在表 {table_name}")

def main():
    """主函數"""
    create_database()
    conn = sqlite3.connect(DATABASE_NAME)
    cursor = conn.cursor()

    for bbs in BBS_LIST:
        table_name = sanitize_table_name(bbs)
        rss_url = f"http://rss.disp.cc/{bbs}.xml"
        print(f"抓取看板 RSS: {bbs}")
        feed = fetch_rss_feed(rss_url)
        if feed:
            parse_and_store(feed, table_name, conn, cursor)
        # 為了避免請求過於頻繁，暫停一秒
        time.sleep(1)

    conn.close()
    print("資料抓取與存儲完成。")

if __name__ == "__main__":
    main()
