# export_zotero_data.py
import sqlite3
import json
import os
from pathlib import Path
import shutil


def export_zotero_highlights():
    """导出Zotero中标记为五星的文献信息"""

    # Zotero数据库路径（需要根据你的系统调整）
    # Windows: C:\Users\[用户名]\Zotero\zotero.sqlite
    # Mac: ~/Zotero/zotero.sqlite
    # Linux: ~/.zotero/zotero.sqlite

    zotero_db_path = os.path.expanduser("~/Zotero/zotero.sqlite")

    try:
        conn = sqlite3.connect(zotero_db_path)
        cursor = conn.cursor()

        # 查询五星级文献
        query = """
                SELECT i.itemID, \
                       i.key, \
                       f.path, \
                       i.libraryID, \
                       t.tagName
                FROM items i
                         JOIN itemTags it ON i.itemID = it.itemID
                         JOIN tags t ON it.tagID = t.tagID
                         LEFT JOIN itemAttachments ia ON i.itemID = ia.parentItemID
                         LEFT JOIN itemData id ON i.itemID = id.itemID
                         LEFT JOIN fields fld ON id.fieldID = fld.fieldID
                         LEFT JOIN itemDataValues idv ON id.valueID = idv.valueID
                WHERE t.tagName = '5stars'
                   OR t.tagName = '★★★★★'
                   OR (t.tagName LIKE '%star%' AND t.tagName LIKE '%5%')
                GROUP BY i.itemID \
                """

        cursor.execute(query)
        articles = cursor.fetchall()

        # 获取PDF路径
        article_data = []
        for article in articles:
            item_id, key, path, library_id, tag = article

            # 获取PDF附件
            pdf_query = """
                        SELECT ia.path, ia.itemID
                        FROM itemAttachments ia
                        WHERE ia.parentItemID = ?
                          AND ia.contentType = 'application/pdf' \
                        """
            cursor.execute(pdf_query, (item_id,))
            pdf_attachments = cursor.fetchall()

            if pdf_attachments:
                for pdf_path, pdf_id in pdf_attachments:
                    # 获取文献元数据
                    meta_query = """
                                 SELECT fld.fieldName, idv.value
                                 FROM itemData id
                                          JOIN fields fld ON id.fieldID = fld.fieldID
                                          JOIN itemDataValues idv ON id.valueID = idv.valueID
                                 WHERE id.itemID = ? \
                                 """
                    cursor.execute(meta_query, (item_id,))
                    metadata = cursor.fetchall()

                    meta_dict = {}
                    for field, value in metadata:
                        meta_dict[field] = value

                    article_data.append({
                        'itemID': item_id,
                        'pdfID': pdf_id,
                        'pdfPath': pdf_path,
                        'metadata': meta_dict,
                        'tag': tag
                    })

        conn.close()

        # 保存导出信息
        with open('zotero_starred_articles.json', 'w', encoding='utf-8') as f:
            json.dump(article_data, f, ensure_ascii=False, indent=2)

        print(f"导出完成，共找到 {len(article_data)} 篇五星文献")
        return article_data

    except Exception as e:
        print(f"错误: {e}")
        return None