#!/usr/bin/env python3
"""
PDF掃描版 → OCR → EPUB
直接從原始 PDF 掃描檔做 OCR，產生完整中文電子書
"""
import fitz
import pytesseract
from PIL import Image
import io
import re
from ebooklib import epub

def ocr_pdf(pdf_path, start=0, end=None):
    """對 PDF 進行 OCR"""
    doc = fitz.open(pdf_path)
    if end is None:
        end = len(doc)
    
    all_text = []
    for page_num in range(start, min(end, len(doc))):
        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_tra+eng')
        all_text.append((page_num + 1, text))
        if (page_num - start + 1) % 10 == 0:
            print(f"  已處理 {page_num - start + 1}/{end - start} 頁")
    
    return all_text

def clean_text(text):
    """清理 OCR 文字"""
    # 去除多餘空格（但保留段落間的）
    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 cleaned_pages:
        # 偵測章節標題
        chapter_match = re.search(r'(第[一二三四五六七八九十百]+章)', 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):
    """建立 EPUB"""
    book = epub.EpubBook()
    book.set_identifier('thompson-organizations-in-action-zh-full')
    book.set_title('行動中的組織：行政理論的社會科學基礎')
    book.set_language('zh')
    book.add_author('詹姆斯·D·湯普森 (James D. Thompson)')
    
    # 樣式
    css_content = '''
    body {
        font-family: "PingFang TC", "Microsoft JhengHei", "Noto Sans TC", 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;
    }
    .page-marker {
        text-align: center;
        color: #999;
        font-size: 0.8em;
        margin: 1em 0;
    }
    '''
    
    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)
        
        # 轉為 HTML 段落
        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 頁）...")
    print("這需要一些時間，請稍候...")
    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完成！")
