import sys
import sqlite3
import requests
import datetime
import json
import html
import re
from bs4 import BeautifulSoup
from selenium import webdriver


def create_tables():
    conn = sqlite3.connect('news.db')
    cursor = conn.cursor()
    # 创建 sources 表
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS sources (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        category TEXT,
        language TEXT,
        name TEXT,
        url TEXT,
        method TEXT,
        form_data TEXT,
        parsing_rules TEXT,
        last_fetch DATETIME
    )
    ''')
    # 创建 articles 表
    cursor.execute("DROP TABLE IF EXISTS articles")
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS articles (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        source_id INTEGER,
        guid TEXT UNIQUE,
        title TEXT,
        link TEXT,
        description TEXT,
        pubDate DATETIME,
        FOREIGN KEY (source_id) REFERENCES sources(id)
    )
    ''')
    conn.commit()
    conn.close()


def get_sources():
    conn = sqlite3.connect('news.db')
    cursor = conn.cursor()
    cursor.execute('SELECT id, category, language, name, url, method, form_data, parsing_rules FROM sources')
    sources = cursor.fetchall()
    conn.close()
    return sources


def update_last_fetch(source_id):
    conn = sqlite3.connect('news.db')
    cursor = conn.cursor()
    cursor.execute('UPDATE sources SET last_fetch = ? WHERE id = ?', (datetime.datetime.now(), source_id))
    conn.commit()
    conn.close()


def insert_article(article_data):
    conn = sqlite3.connect('news.db')
    cursor = conn.cursor()
    try:
        cursor.execute('''
        INSERT INTO articles (source_id, guid, title, link, description, pubDate)
        VALUES (?, ?, ?, ?, ?, ?)
        ''', article_data)
        conn.commit()
        print(f"插入文章：{article_data[2]} (GUID: {article_data[1]})")
    except sqlite3.IntegrityError as e:
        print(f"插入文章时发生错误：{e}，GUID：{article_data[1]}")
    finally:
        conn.close()


def get_existing_guids(source_id):
    conn = sqlite3.connect('news.db')
    cursor = conn.cursor()
    cursor.execute('SELECT guid FROM articles WHERE source_id = ?', (source_id,))
    existing = cursor.fetchall()
    existing_guids = set([item[0] for item in existing if item[0]])
    conn.close()
    return existing_guids




def extract_field(element, field_rule):
    selector = field_rule.get('selector')
    attribute = field_rule.get('attribute', 'text')
    prefix = field_rule.get('prefix', '')
    regex = field_rule.get('regex', '')
    attribute_filter = field_rule.get('attribute_filter', {})

    if not selector:
        return ''

    target = element.select_one(selector)
    if not target:
        return ''

    # 处理 attribute_filter
    if attribute_filter:
        filter_keys = attribute_filter.get('keys', [])
        # 检查每个关键字是否作为属性存在于目标元素中
        for key in filter_keys:
            if not target.has_attr(key):
                return ''  # 如果任何一个关键字属性不存在，则返回空字符串

    # 提取属性值或文本内容
    if attribute == 'text':
        value = target.get_text(strip=True)
    else:
        value = target.get(attribute, '').strip()

    # 应用正则表达式（如果有）
    if regex:
        match = re.search(regex, value)
        if match:
            value = match.group(1)
        else:
            value = ''

    # 添加前缀（如果有）
    if prefix:
        value = prefix + value

    return value.strip()

def parse_pubdate(pubDate_str, date_format=None):
    if not pubDate_str:
        return None

    # 使用正則表達式提取日期部分
    date_match = re.search(r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}(:\d{2})?", pubDate_str)
    if date_match:
        pubDate_str = date_match.group(0)  # 提取匹配的日期時間字串

    now = datetime.datetime.now()

    # 檢查是否為相對時間格式（例如 "2小時前", "3天前"）
    relative_time_patterns = [
        (r"(\d+)\s*(秒前|seconds? ago)", "seconds"),
        (r"(\d+)\s*(分鐘前|minutes? ago)", "minutes"),
        (r"(\d+)\s*(小時前|hours? ago)", "hours"),
        (r"(\d+)\s*(天前|days? ago)", "days"),
        (r"(\d+)\s*(周前|weeks? ago)", "weeks"),
        (r"(\d+)\s*(月前|months? ago)", "months"),
        (r"(\d+)\s*(年前|years? ago)", "years")
    ]

    for pattern, time_unit in relative_time_patterns:
        match = re.match(pattern, pubDate_str)
        if match:
            value = int(match.group(1))
            if time_unit == "seconds":
                pubDate = now - datetime.timedelta(seconds=value)
            elif time_unit == "minutes":
                pubDate = now - datetime.timedelta(minutes=value)
            elif time_unit == "hours":
                pubDate = now - datetime.timedelta(hours=value)
            elif time_unit == "days":
                pubDate = now - datetime.timedelta(days=value)
            elif time_unit == "weeks":
                pubDate = now - datetime.timedelta(weeks=value)
            elif time_unit == "months":
                pubDate = now - datetime.timedelta(days=value * 30)  # 粗略估計一個月為30天
            elif time_unit == "years":
                pubDate = now - datetime.timedelta(days=value * 365)  # 粗略估計一年為365天
            return pubDate

    # 若非相對時間格式，嘗試使用提供的日期格式
    if date_format:
        try:
            pubDate = datetime.datetime.strptime(pubDate_str, date_format)
            return pubDate
        except ValueError as e:
            print(f"解析发布日期失败：{e}，pubDate_str：{pubDate_str}")
            return None

    print(f"未知的日期格式：{pubDate_str}")
    return None


def fetch_and_parse_source(source, keyword):
    source_id, category, language, name, url, method, form_data, parsing_rules_json = source

    # 將 keyword 附加到 url
    url = url + keyword

    # 加载解析规则
    try:
        parsing_rules = json.loads(parsing_rules_json)
    except json.JSONDecodeError as e:
        print(f"解析规则错误，来源 {name}：{e}")
        return

    # 请求数据
    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:
        if method.upper() == 'GET':
            response = requests.get(url, headers=headers)
        elif method.upper() == 'POST':
            data = json.loads(form_data) if form_data else {}
            response = requests.post(url, data=data, headers=headers)
        else:
            print(f"不支持的方法 {method}，来源 {name}")
            return
    except Exception as e:
        print(f"获取数据失败，来源 {name}：{e}")
        return

    content = response.text  # 获取文本内容

    # 预处理
    preprocessing_steps = parsing_rules.get('preprocessing', [])
    for step in preprocessing_steps:
        find_str = step.get('find')
        replace_str = step.get('replace', '')
        if find_str is not None:
            content = content.replace(find_str, replace_str)

    # 解析内容
    #print(content)
    soup = BeautifulSoup(content, 'html.parser')

    # 获取容器
    container_selector = parsing_rules.get('container_selector', '')
    if container_selector:
        container = soup.select_one(container_selector)
    else:
        container = soup

    if not container:
        print(f"未找到容器，来源 {name}，选择器 {container_selector}")
        return

    # 获取文章列表
    article_selector = parsing_rules.get('article_selector', '')
    if article_selector:
        articles = container.select(article_selector)
    else:
        articles = [container]

    if not articles:
        print(f"未找到文章，来源 {name}，选择器 {article_selector}")
        return

    existing_guids = get_existing_guids(source_id)

    count = 0
    for article in articles:
        fields = parsing_rules.get('fields', {})
        guid_field = fields.get('guid', {})
        title_field = fields.get('title', {})
        link_field = fields.get('link', {})
        description_field = fields.get('description', {})
        pubDate_field = fields.get('pubDate', {})

        # 提取 GUID
        guid = extract_field(article, guid_field)
        if not guid:
            print(f"跳过没有 GUID 的文章，来源 {name}")
            continue

        if guid in existing_guids:
            print(f"GUID 已存在，跳过：{guid}")
            continue

        # 提取其他字段
        title = extract_field(article, title_field)
        link = extract_field(article, link_field)
        description = extract_field(article, description_field)
        pubDate_str = extract_field(article, pubDate_field)
        pubDate = parse_pubdate(pubDate_str, pubDate_field.get('date_format', '%Y-%m-%d %H:%M:%S'))

        # 插入文章
        article_data = (source_id, guid, title, link, description, pubDate)
        insert_article(article_data)

        count += 1

    update_last_fetch(source_id)
    print(f"来源 {name} 处理完成，插入 {count} 篇文章。")



def renew_sources(keyword):
    sources = get_sources()
    if not sources:
        print("没有自定义来源需要处理。")
        return
    for source in sources:
        source_id, category, language, name, url, method, form_data, parsing_rules_json = source
        print(f"处理来源：{name} ({url})")
        fetch_and_parse_source(source, keyword)


if __name__ == "__main__":
    create_tables()

    # 接收命令列參數
    if len(sys.argv) > 1:
        keyword = sys.argv[1]
    else:
        print("請提供一個關鍵字作為參數。")
        sys.exit(1)

    renew_sources(keyword)