#!/usr/bin/env python3
"""
用修正後的文字重建 EPUB
處理不規則的章節標題格式
"""
import re
from ebooklib import epub

# 讀取修正後的文字
with open('/Users/lingochen/Desktop/ocr_fixed.txt', 'r', encoding='utf-8') as f:
    full_text = f.read()

# 更寬容的章節標題匹配
# 支持: "第一章 第一章 研究組織的战略", "第一章 研究組織的战略", "第一章 " 研究組織的战略"
chapter_pattern = re.compile(
    r'^(第[一二三四五六七八九十零百\d]+章)\s*(?:第[一二三四五六七八九十零百\d]+章\s*)?(?:"\s*)?([^\n]{2,50})',
    re.MULTILINE
)

# 找出所有章節標題的位置
chapters = []
last_pos = 0

for match in chapter_pattern.finditer(full_text):
    pos = match.start()
    if pos > last_pos:
        # 之前有前言或其他內容
        content = full_text[last_pos:pos].strip()
        if content:
            # 提取前言標題（通常是第一個非章節內容）
            title_match = re.match(r'^(.{2,30})', content)
            if title_match:
                title = title_match.group(1).strip()
            else:
                title = '前言'
            chapters.append((title, content))
    
    # 提取章節標題
    chapter_num = match.group(1)
    chapter_title = match.group(2).strip()
    if chapter_title.startswith('"') or chapter_title.startswith('「'):
        chapter_title = chapter_title[1:].strip()
    
    full_title = f'{chapter_num} {chapter_title}'
    chapters.append((full_title, ''))
    last_pos = pos + len(match.group(0))

# 添加最後一個章節
if last_pos < len(full_text):
    content = full_text[last_pos:].strip()
    if content:
        title = f'附錄'
        chapters.append((title, content))

print(f'偵測到 {len(chapters)} 個章節')

# 將章節內容填充到標題後
final_chapters = []
for i, (title, content) in enumerate(chapters):
    if not content and i + 1 < len(chapters):
        # 這個章節沒有內容，可能是因為標題被誤判
        # 跳過
        continue
    final_chapters.append((title, content))

print(f'實際章節數: {len(final_chapters)}')
for i, (title, content) in enumerate(final_chapters):
    print(f'  {i+1}. {title[:50]}... ({len(content)} 字)')

# 建立 EPUB
book = epub.EpubBook()
book.set_identifier('thompson-organizations-in-action-zh-corrected-v2')
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, (title, content) in enumerate(final_chapters):
    # 分割段落
    paragraphs = content.split('\n\n')
    html_parts = []
    for p in paragraphs:
        p = p.strip()
        if p:
            # 轉義 HTML
            p = p.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
            html_parts.append(f'<p>{p}</p>')
    html_content = '\n'.join(html_parts)
    
    chapter = epub.EpubHtml(title=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>{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'ch{i+1:02d}.xhtml', t, f'ch{i+1}')
           for i, (t, _) in enumerate(final_chapters)]
book.spine = ['nav'] + epub_chapters
book.add_item(epub.EpubNcx())
book.add_item(epub.EpubNav())

output = '/Users/lingochen/Desktop/行動中的組織_修正版v2.epub'
epub.write_epub(output, book)
print(f'\nEPUB 已儲存: {output}')
print(f'共 {len(final_chapters)} 個章節')
