#!/usr/bin/env python3
"""
將行動中的組織_全文.txt (OCR掃描版) 轉為 EPUB
- 清除每個字之間的空格（OCR 噪音）
- 保留頁面結構
- 生成可讀的中文電子書
"""
import re
from ebooklib import epub

def clean_ocr(text):
    """清除 OCR 噪音：字間空格、亂碼"""
    # 去除每字之間的空格 (OCR 特有的問題)
    # 中文字 + 空格 + 中文字 的模式
    text = re.sub(r'([\u4e00-\u9fff])\s+([\u4e00-\u9fff])', r'\1\2', text)
    # 重複執行幾次以處理連續的
    for _ in range(5):
        text = re.sub(r'([\u4e00-\u9fff])\s+([\u4e00-\u9fff])', r'\1\2', text)
    # 修正常見 OCR 錯誤
    text = text.replace('勹', '的').replace('圂', '織').replace('紉', '織')
    text = text.replace('理泊', '理論').replace('科孝', '科學').replace('基破', '基礎')
    text = text.replace('社金', '社會').replace('組鋇', '組織').replace('組縝', '組織')
    text = text.replace('活普森', '湯普森').replace('淳普森', '湯普森')
    text = text.replace('行勁', '行動').replace('行勤', '行動')
    return text.strip()

def split_by_page(filepath):
    """按頁面分割內容"""
    with open(filepath, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 找到所有頁面標記
    pages = re.split(r'---\s*第\s*\d+\s*頁\s*---', content)
    # 移除空頁面
    pages = [p.strip() for p in pages if p.strip()]
    return pages

def pages_to_chapters(pages):
    """將頁面分組為章節"""
    chapters = []
    current_title = "前言"
    current_content = []
    
    for page in pages:
        cleaned = clean_ocr(page)
        # 檢測章節標題
        if re.search(r'第[一二三四五六七八九十]+章', cleaned):
            if current_content:
                chapters.append((current_title, '\n\n'.join(current_content)))
            # 提取章節標題
            match = re.search(r'(第[一二三四五六七八九十]+章[^\\n]*)', cleaned)
            if match:
                current_title = match.group(1).strip()
            else:
                current_title = f"第 {len(chapters)+1} 章"
            current_content = []
        
        current_content.append(cleaned)
    
    # 加入最後一個章節
    if current_content:
        chapters.append((current_title, '\n\n'.join(current_content)))
    
    return chapters

def create_epub(chapters, output_path):
    """建立 EPUB 電子書"""
    book = epub.EpubBook()
    book.set_identifier('thompson-organizations-in-action-zh-2026')
    book.set_title('行動中的組織：行政理論的社會科學基礎')
    book.set_language('zh')
    book.add_author('詹姆斯·D·湯普森 (James D. Thompson)')
    
    # 定義樣式
    style = '''
    body {
        font-family: "PingFang TC", "Microsoft JhengHei", sans-serif;
        line-height: 1.8;
        margin: 1.5em;
        color: #333;
    }
    h1 {
        font-size: 1.8em;
        color: #1a1a2e;
        border-bottom: 2px solid #e94560;
        padding-bottom: 0.3em;
    }
    h2 {
        font-size: 1.3em;
        color: #16213e;
        margin-top: 1.5em;
    }
    p {
        text-indent: 2em;
        margin: 0.8em 0;
        text-align: justify;
    }
    .page-break {
        page-break-before: always;
    }
    '''
    
    css = epub.EpubItem(uid='style', file_name='style/default.css', 
                       media_type='text/css', content=style.encode('utf-8'))
    book.add_item(css)
    
    # 建立章節
    epub_chapters = []
    for i, (title, content) in enumerate(chapters):
        chapter = epub.EpubHtml(title=title, file_name=f'chapter_{i+1:02d}.xhtml', lang='zh')
        
        # 轉換為 HTML
        paragraphs = content.split('\n\n')
        html_content = ''.join(f'<p>{p}</p>' for p in paragraphs if p.strip())
        chapter.content = f'''
        <html>
        <head>
            <link rel="stylesheet" href="style/default.css" />
        </head>
        <body>
            <h1>{title}</h1>
            {html_content}
        </body>
        </html>
        '''.encode('utf-8')
        
        chapter.add_item(css)
        book.add_item(chapter)
        epub_chapters.append(chapter)
    
    # 設定目錄和書脊
    book.toc = [epub.Link(f'chapter_{i+1:02d}.xhtml', title, f'ch{i+1}') 
               for i, (title, _) 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"EPUB 已建立：{output_path}")

def main():
    input_file = '/Users/lingochen/Desktop/行動中的組織_全文.txt'
    output_file = '/Users/lingochen/Desktop/行動中的組織_完整版.epub'
    
    print("正在讀取 OCR 內容...")
    pages = split_by_page(input_file)
    print(f"共 {len(pages)} 頁")
    
    print("正在分組為章節...")
    chapters = pages_to_chapters(pages)
    print(f"共 {len(chapters)} 個章節")
    
    print("正在建立 EPUB...")
    create_epub(chapters, output_file)
    
    print("完成！")

if __name__ == '__main__':
    main()
