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

# 配置部分
DATABASE_NAME = 'dcard.db'  # 更新資料庫名稱
# Dcard 的各個版區 API 端點
Dcard_SECTIONS = [
    "sex", "makeup", "relationship", "cooking",
    "pet", "study", "programming", "travel",
    "daily", "fitness", "movies", "music",
    "books", "games", "photography", "fashion",
    "tech", "health", "sports", "business"
]

# Dcard API 基本 URL
Dcard_API_BASE_URL = "https://www.dcard.tw/service/api/v2/forums/"

def create_database(sections):
    """建立SQLite資料庫和各版區的表格"""
    conn = sqlite3.connect(DATABASE_NAME)
    cursor = conn.cursor()
    for section in sections:
        # 清理表名，確保符合SQLite命名規則
        table_name = re.sub(r'\W+', '_', section)
        cursor.execute(f'''
            CREATE TABLE IF NOT EXISTS "{table_name}" (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                source TEXT,
                title TEXT,
                link TEXT,
                pubDate TEXT,
                xcomment INTEGER,
                xlike INTEGER,
                description TEXT
            )
        ''')
    conn.commit()
    conn.close()

def fetch_dcard_posts(section, limit=30, before=None):
    """
    使用 Dcard API 抓取指定版區的文章資料
    :param section: 版區名稱
    :param limit: 每次抓取的文章數量（最大 30）
    :param before: 抓取指定文章 ID 之前的文章（用於分頁）
    :return: JSON 格式的文章列表
    """
    url = f"{Dcard_API_BASE_URL}{section}/posts"
    params = {
        "popular": "false",  # 是否抓取熱門文章
        "limit": limit,
        "before": before
    }
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36"
    }
    try:
        response = requests.get(url, params=params, headers=headers, timeout=10)
        response.raise_for_status()
        posts = response.json()
        # 篩選指定版區的文章
        section_posts = [post for post in posts if post.get('section', {}).get('name') == section]
        return section_posts
    except requests.RequestException as e:
        print(f"請求異常: {section} - {e}")
        return []

def parse_and_store(posts, section, conn, cursor):
    """解析文章資料並存入 SQLite"""
    table_name = re.sub(r'\W+', '_', section)  # 清理表名，確保符合SQLite命名規則
    for post in posts:
        title = post.get('title', '').strip()
        link = post.get('url', '').strip()
        pub_date = post.get('createdAt', '')
        xcomment = post.get('commentCount', 0)
        xlike = post.get('likeCount', 0)
        description = post.get('excerpt', '').strip()  # 摘要內容

        # 插入資料
        try:
            cursor.execute(f'''
                INSERT OR IGNORE INTO "{table_name}" (
                    source, title, link, pubDate,
                    xcomment, xlike, description
                ) VALUES (?, ?, ?, ?, ?, ?, ?)
            ''', (
                section, title, link, pub_date,
                xcomment, xlike, description
            ))
            conn.commit()
            print(f"插入資料於 {section}: {title}")
        except sqlite3.IntegrityError:
            print(f"重複資料略過於 {section}: {title}")

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

    for section in Dcard_SECTIONS:
        print(f"抓取版區資料: {section}")
        all_posts = []
        before = None
        while True:
            posts = fetch_dcard_posts(section, limit=30, before=before)
            if not posts:
                break
            all_posts.extend(posts)
            # 設定下一次抓取的基準 ID 為最後一篇文章的 ID
            before = posts[-1]['id']
            # 為了避免請求過於頻繁，暫停一秒
            time.sleep(1)
            # 可根據需要設定抓取的總篇數，這裡僅抓取最新的 100 篇
            if len(all_posts) >= 100:
                break
        if all_posts:
            parse_and_store(all_posts, section, conn, cursor)
        else:
            print(f"No posts found for section: {section}")
        # 為了避免請求過於頻繁，暫停一秒
        time.sleep(1)

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

if __name__ == "__main__":
    main()
