#!/usr/bin/env python3
"""PDF掃描版 → OCR (簡中) → EPUB"""
import fitz
import pytesseract
from PIL import Image
import io
import re
from ebooklib import epub

def ocr_pdf(pdf_path):
    doc = fitz.open(pdf_path)
    total = len(doc)
    all_text = []
    for page_num in range(total):
        page = doc[page_num]
        pix = page.get_pixmap(dpi=200)
        img = Image.open(io.BytesIO(pix.tobytes("png")))
        text = pytesseract.image_to_string(img, lang='chi_sim+eng')
        all_text.append((page_num + 1, text))
        if (page_num + 1) % 10 == 0:
            print(f"  已處理 {page_num + 1}/{total} 頁")
    return all_text

def clean_text(text):
    lines = text.split('\n')
    cleaned = []
    for line in lines:
        line = line.strip()
        if not line:
            cleaned.append('')
            continue
        line = re.sub(r'([\u4e00-\u9fff])\s+([\u4e00-\u9fff])', r'\1\2', line)
        for _ in range(3):
            line = re.sub(r'([\u4e00-\u9fff])\s+([\u4e00-\u9fff])', r'\1\2', line)
        cleaned.append(line)
    return '\n'.join(cleaned)

def detect_chapters(pages):
    chapters = []
    current_chapter = "前言"
    current_pages = []
    for page_num, text in pages:
        chapter_match = re.search(r'(第[一二三四五六七八九十百零\d]+章)', text)
        if chapter_match:
            if current_pages:
                chapters.append((current_chapter, current_pages))
            current_chapter = chapter_match.group(1)
            current_pages = []
        current_pages.append((page_num, text))
    if current_pages:
        chapters.append((current_chapter, current_pages))
    return chapters

def create_epub(chapters, output_path):
    book = epub.EpubBook()
    book.set_identifier('thompson-organizations-in-action-zh')
    book.set_title('行动中的组织：行政理论的社会科学基础')
    book.set_language('zh')
    book.add_author('詹姆斯·D·汤普森 (James D. Thompson)')
    
    css_content = '''
    body { font-family: "PingFang SC", "Microsoft YaHei", "Noto Sans SC", sans-serif; line-height: 1.8; margin: 1.5em; color: #333; }
    h1 { font-size: 1.6em; color: #1a1a2e; border-bottom: 2px solid #e94560; padding-bottom: 0.3em; margin-top: 2em; }
    h2 { font-size: 1.2em; color: #16213e; margin-top: 1.5em; }
    p { text-indent: 2em; margin: 0.6em 0; text-align: justify; }
    '''
    css = epub.EpubItem(uid='style', file_name='style/default.css',
                       media_type='text/css', content=css_content.encode('utf-8'))
    book.add_item(css)
    
    epub_chapters = []
    for i, (ch_title, pages) in enumerate(chapters):
        full_text = '\n\n'.join(text for _, text in pages)
        cleaned = clean_text(full_text)
        paragraphs = cleaned.split('\n\n')
        html_parts = []
        for p in paragraphs:
            p = p.strip()
            if p:
                html_parts.append(f'<p>{p}</p>')
        html_content = '\n'.join(html_parts)
        
        chapter = epub.EpubHtml(title=ch_title, file_name=f'ch{i+1:02d}.xhtml', lang='zh')
        chapter.content = f'''<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head><link rel="stylesheet" href="style/default.css"/></head>
<body>
<h1>{ch_title}</h1>
{html_content}
</body>
</html>'''.encode('utf-8')
        chapter.add_item(css)
        book.add_item(chapter)
        epub_chapters.append(chapter)
        print(f"  章节 {i+1}: {ch_title} ({len(pages)} 页)")
    
    book.toc = [epub.Link(f'ch{i+1:02d}.xhtml', t, f'ch{i+1}')
               for i, (t, _) in enumerate(chapters)]
    book.spine = ['nav'] + epub_chapters
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())
    epub.write_epub(output_path, book)
    print(f"\nEPUB 已储存：{output_path}")

if __name__ == '__main__':
    pdf_path = "/Users/lingochen/.openclaw/media/inbound/行動中的組織---784ef0bf-9749-4e08-a1ab-4d99b2a8725a.pdf"
    output_path = "/Users/lingochen/Desktop/行动中的组织_简中版.epub"
    
    print("正在 OCR 处理 PDF（250 页，简体中文模式）...")
    pages = ocr_pdf(pdf_path)
    
    print("\n正在清理文字...")
    cleaned_pages = [(pn, clean_text(text)) for pn, text in pages]
    
    print("正在检测章节...")
    chapters = detect_chapters(cleaned_pages)
    print(f"检测到 {len(chapters)} 个章节")
    
    print("正在建立 EPUB...")
    create_epub(chapters, output_path)
    print("\n完成！")
