# -*- coding: utf-8 -*-
#!/usr/bin/env python3
"""
建立標準 EPUB 3.0
"""
import re
import os
import zipfile

def create_epub(text_file, output_file):
    with open(text_file, 'r', encoding='utf-8') as f:
        text = f.read()
    
    # 分割章節
    chapter_pattern = r'^(第[一二三四五六七八九十百零]+章\s+.+)$'
    parts = re.split(f'({chapter_pattern})', text, flags=re.MULTILINE)
    
    chapters = []
    i = 0
    while i < len(parts):
        chunk = parts[i].strip()
        if re.match(chapter_pattern, chunk) and i + 1 < len(parts):
            title = chunk
            content = parts[i + 1].strip() if i + 1 < len(parts) else ''
            chapters.append((title, content))
            i += 2
        elif chunk and len(chunk) > 50:
            chapters.append(('前言', chunk))
            i += 1
        else:
            i += 1
    
    if len(chapters) < 5:
        paragraphs = [p.strip() for p in text.split('\n\n') if len(p.strip()) > 50]
        for j in range(0, len(paragraphs), 10):
            chunk = '\n\n'.join(paragraphs[j:j+10])
            chapters.append((f'段落 {j//10+1}', chunk))
    
    print(f'共 {len(chapters)} 個章節')
    
    # 建立 EPUB zip
    with zipfile.ZipFile(output_file, 'w', zipfile.ZIP_DEFLATED) as epub:
        # mimetype（必須第一個，不壓縮）
        epub.writestr('mimetype', 'application/epub+zip', compress_type=zipfile.ZIP_STORED)
        
        # META-INF/container.xml
        container = '''<?xml version="1.0" encoding="UTF-8"?>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
  <rootfiles>
    <rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
  </rootfiles>
</container>'''
        epub.writestr('META-INF/container.xml', container)
        
        # content.opf
        manifest_items = ''
        spine_items = ''
        toc_nav = ''
        for i, (title, _) in enumerate(chapters):
            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'
            toc_nav += f'      <li><a href="chapter{i}.xhtml">{title}</a></li>\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-Hant</dc:language>
    <dc:identifier id="uid">thompson-organizations-in-action-zh-final-v2</dc:identifier>
    <meta property="dcterms:modified">2026-06-13T12:00:00Z</meta>
  </metadata>
  <manifest>
    <item id="ncx" href="toc.ncx" media-type="application/x-dtbncx+xml"/>
    <item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/>
{manifest_items}  </manifest>
  <spine toc="ncx">
{spine_items}  </spine>
</package>'''
        epub.writestr('OEBPS/content.opf', opf)
        
        # toc.ncx
        nav_points = ''
        for i, (title, _) in enumerate(chapters):
            safe_title = title.replace('&', '&amp;').replace('<', '&lt;')
            nav_points += f'''    <navPoint id="navPoint-{i+1}" playOrder="{i+1}">
      <navLabel><text>{safe_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-v2"/>
    <meta name="dtb:depth" content="1"/>
    <meta name="dtb:totalPageCount" content="0"/>
    <meta name="dtb:maxPageNumber" content="0"/>
  </head>
  <docTitle><text>行動中的組織</text></docTitle>
  <navMap>
{nav_points}  </navMap>
</ncx>'''
        epub.writestr('OEBPS/toc.ncx', ncx)
        
        # nav.xhtml
        nav_items = ''
        for i, (title, _) in enumerate(chapters):
            safe_title = title.replace('&', '&amp;').replace('<', '&lt;')
            nav_items += f'        <li><a href="chapter{i}.xhtml">{safe_title}</a></li>\n'
        
        nav_xhtml = f'''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">
<head><title>目錄</title></head>
<body>
  <nav epub:type="toc">
    <h1>目錄</h1>
    <ol>
{nav_items}    </ol>
  </nav>
</body>
</html>'''
        epub.writestr('OEBPS/nav.xhtml', nav_xhtml)
        
        # 章節 XHTML
        for i, (title, content) in enumerate(chapters):
            safe_title = title.replace('&', '&amp;').replace('<', '&lt;')
            paragraphs = content.split('\n\n')
            body = f'    <h1>{safe_title}</h1>\n'
            for para in paragraphs:
                para = para.strip()
                if para:
                    safe_para = para.replace('&', '&amp;').replace('<', '&lt;')
                    # 保留換行
                    safe_para = safe_para.replace('\n', '<br/>')
                    body += f'    <p>{safe_para}</p>\n'
            
            xhtml = f'''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>{safe_title}</title>
  <style>
    body {{ font-family: serif; margin: 1em; line-height: 1.8; }}
    h1 {{ font-size: 1.5em; margin-bottom: 1em; }}
    p {{ margin: 0.5em 0; text-indent: 2em; }}
  </style>
</head>
<body>
{body}</body>
</html>'''
            epub.writestr(f'OEBPS/chapter{i}.xhtml', xhtml)
    
    size = os.path.getsize(output_file)
    print(f'EPUB: {output_file} ({size:,} bytes)')

if __name__ == '__main__':
    create_epub(
        '/Users/lingochen/Desktop/ocr_final_clean.txt',
        '/Users/lingochen/Desktop/行動中的組織_最終版v2.epub'
    )
