# -*- coding: utf-8 -*-
#!/usr/bin/env python3
"""
用修正後的文字重建 EPUB
"""
import re
import os

def create_epub(text, output_file):
    """建立 EPUB"""
    # 分割章節
    chapter_pattern = r'^(第[一二三四五六七八九十百千]+章\s+.+)$'
    chapters = re.split(f'({chapter_pattern})', text, flags=re.MULTILINE)
    
    # 合併標題和內容
    merged = []
    i = 0
    while i < len(chapters):
        chunk = chapters[i].strip()
        if re.match(chapter_pattern, chunk) and i + 1 < len(chapters):
            content = chunk + '\n\n' + chapters[i + 1].strip()
            merged.append(content)
            i += 2
        elif chunk:
            merged.append(chunk)
            i += 1
        else:
            i += 1
    
    # 過濾太短的
    chapter_list = [c for c in merged if len(c) > 100]
    
    # 如果章節太少，用原始分割
    if len(chapter_list) < 10:
        chapter_list = [c.strip() for c in text.split('\n\n') if len(c.strip()) > 100]
    
    print(f'共 {len(chapter_list)} 個章節')
    
    # 建立 EPUB
    epub_dir = '/Users/lingochen/Desktop/epub_temp'
    os.makedirs(f'{epub_dir}/OEBPS', exist_ok=True)
    
    # content.opf
    manifest_items = ''
    spine_items = ''
    for i, ch in enumerate(chapter_list):
        manifest_items += f'    <item id="ch{i}" href="chapter{i}.xhtml" media-type="application/xhtml+xml"/>\n'
        spine_items += f'    <itemref idref="ch{i}"/>\n'
    
    opf = f'''<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="uid">
  <metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:title>行動中的組織</dc:title>
    <dc:creator>詹姆斯·湯普森</dc:creator>
    <dc:language>zh-TW</dc:language>
    <dc:identifier id="uid">thompson-organizations-in-action-zh-final</dc:identifier>
  </metadata>
  <manifest>
    <item id="ncx" href="toc.ncx" media-type="application/x-dtbncx+xml"/>
{manifest_items}  </manifest>
  <spine toc="ncx">
{spine_items}  </spine>
</package>'''
    
    with open(f'{epub_dir}/OEBPS/content.opf', 'w', encoding='utf-8') as f:
        f.write(opf)
    
    # toc.ncx
    nav_points = ''
    for i, ch in enumerate(chapter_list):
        title = ch[:50].split('\n')[0]
        nav_points += f'''    <navPoint id="navPoint-{i+1}" playOrder="{i+1}">
      <navLabel><text>{title}</text></navLabel>
      <content src="chapter{i}.xhtml"/>
    </navPoint>\n'''
    
    ncx = f'''<?xml version="1.0" encoding="UTF-8"?>
<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1">
  <head><meta name="dtb:uid" content="thompson-organizations-in-action-zh-final"/></head>
  <docTitle><text>行動中的組織</text></docTitle>
  <navMap>
{nav_points}  </navMap>
</ncx>'''
    
    with open(f'{epub_dir}/OEBPS/toc.ncx', 'w', encoding='utf-8') as f:
        f.write(ncx)
    
    # 章節 XHTML
    for i, ch in enumerate(chapter_list):
        paragraphs = ch.split('\n\n')
        content = ''
        for j, para in enumerate(paragraphs):
            para = para.strip()
            if not para:
                continue
            if j == 0 and re.match(r'第[一二三四五六七八九十百千]+章', para):
                content += f'    <h1>{para}</h1>\n'
            else:
                content += f'    <p>{para}</p>\n'
        
        xhtml = f'''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>行動中的組織</title></head>
<body>
{content}</body>
</html>'''
        
        with open(f'{epub_dir}/OEBPS/chapter{i}.xhtml', 'w', encoding='utf-8') as f:
            f.write(xhtml)
    
    # mimetype
    with open(f'{epub_dir}/mimetype', 'w') as f:
        f.write('application/epub+zip')
    
    # 打包成 EPUB
    os.system(f'cd {epub_dir} && zip -0 -X "{output_file}" mimetype')
    os.system(f'cd {epub_dir} && zip -r -X "{output_file}" OEBPS/')
    
    # 清理
    os.system(f'rm -rf {epub_dir}')
    
    size = os.path.getsize(output_file)
    print(f'EPUB: {output_file} ({size:,} bytes)')

def main():
    text_file = '/Users/lingochen/Desktop/ocr_final_clean.txt'
    epub_file = '/Users/lingochen/Desktop/行動中的組織_最終版.epub'
    
    with open(text_file, 'r', encoding='utf-8') as f:
        text = f.read()
    
    print(f'文字: {len(text)} 字')
    create_epub(text, epub_file)

if __name__ == '__main__':
    main()
