# AI生成
#!/usr/bin/env python3
"""
性能优化器
大型 PPT 分批生成 + 并行渲染,最后合并。
"""

import argparse
import json
import os
import sys
import time
from pathlib import Path
from multiprocessing import Pool, cpu_count

try:
    from pptx import Presentation
    from pptx.util import Inches, Pt, Emu
    HAS_PPTX = True
except ImportError:
    HAS_PPTX = False


def create_slide_from_content(prs, page_content):
    """根据页面内容创建幻灯片"""
    layout = prs.slide_layouts[1]  # Title and Content
    slide = prs.slides.add_slide(layout)

    # 设置标题
    if slide.shapes.title:
        slide.shapes.title.text = page_content.get("title", "")

    # 设置内容
    if len(slide.placeholders) > 1:
        body = slide.placeholders[1]
        tf = body.text_frame
        tf.clear()

        items = page_content.get("items", [])
        for i, item in enumerate(items):
            if i == 0:
                tf.paragraphs[0].text = item
            else:
                p = tf.add_paragraph()
                p.text = item

    return slide


def generate_batch(batch_data):
    """生成一批幻灯片(在子进程中执行)"""
    batch_idx, pages, temp_dir = batch_data

    if not HAS_PPTX:
        return {"error": "python-pptx not installed", "batch_idx": batch_idx}

    # 创建临时 PPTX
    prs = Presentation()
    for page in pages:
        create_slide_from_content(prs, page)

    # 保存临时文件
    temp_file = os.path.join(temp_dir, f"batch_{batch_idx}.pptx")
    prs.save(temp_file)

    return {
        "batch_idx": batch_idx,
        "pages": len(pages),
        "temp_file": temp_file,
    }


def merge_pptx(batch_files, output_path):
    """合并多个 PPTX 文件"""
    if not batch_files:
        return {"error": "没有批次文件可合并"}

    # 以第一个文件为基础
    merged = Presentation(batch_files[0])

    # 逐个添加后续文件的幻灯片
    for batch_file in batch_files[1:]:
        batch_prs = Presentation(batch_file)
        for slide in batch_prs.slides:
            # 创建新幻灯片并复制内容
            new_slide = merged.slides.add_slide(merged.slide_layouts[1])

            # 复制文本内容
            for shape in slide.shapes:
                if shape.has_text_frame:
                    # 在新幻灯片上添加文本框
                    for para in shape.text_frame.paragraphs:
                        if para.text.strip():
                            if new_slide.shapes.title and not new_slide.shapes.title.text:
                                new_slide.shapes.title.text = para.text
                            elif len(new_slide.placeholders) > 1:
                                body = new_slide.placeholders[1]
                                if not body.text_frame.paragraphs[0].text:
                                    body.text_frame.paragraphs[0].text = para.text
                                else:
                                    p = body.text_frame.add_paragraph()
                                    p.text = para.text

    merged.save(output_path)
    return {"merged_slides": len(merged.slides), "output_file": output_path}


def optimize_generation(content_path, batch_size=5, workers=None, output_path=None):
    """执行分批并行生成"""
    if not HAS_PPTX:
        return {"error": "python-pptx not installed. Run: pip install python-pptx"}

    # 读取内容
    with open(content_path, "r", encoding="utf-8") as f:
        content = json.load(f)

    pages = content.get("pages", content if isinstance(content, list) else [])
    total_pages = len(pages)

    if workers is None:
        workers = max(cpu_count() - 1, 1)

    # 拆分批次
    batches = []
    for i in range(0, total_pages, batch_size):
        batch_pages = pages[i:i + batch_size]
        batches.append((i // batch_size, batch_pages, str(Path(content_path).parent)))

    total_batches = len(batches)

    # 记时开始
    start_time = time.time()

    # 并行生成
    with Pool(workers) as pool:
        results = pool.map(generate_batch, batches)

    generation_time = time.time() - start_time

    # 合并
    batch_files = [r["temp_file"] for r in results if "temp_file" in r]

    if not output_path:
        output_path = str(Path(content_path).with_suffix("").with_suffix(".pptx"))

    merge_start = time.time()
    merge_result = merge_pptx(batch_files, output_path)
    merge_time = time.time() - merge_start

    total_time = time.time() - start_time

    # 估算单进程耗时(用于对比)
    estimated_sequential_time = total_time * workers  # 粗略估算

    # 清理临时文件
    for temp_file in batch_files:
        try:
            os.remove(temp_file)
        except OSError:
            pass

    result = {
        "total_pages": total_pages,
        "batch_size": batch_size,
        "total_batches": total_batches,
        "workers": workers,
        "generation_time_seconds": round(generation_time, 2),
        "merge_time_seconds": round(merge_time, 2),
        "total_time_seconds": round(total_time, 2),
        "estimated_sequential_time_seconds": round(estimated_sequential_time, 2),
        "estimated_speedup": round(estimated_sequential_time / total_time, 2) if total_time > 0 else 0,
        "output_file": output_path,
        "total_slides_in_output": merge_result.get("merged_slides", 0),
    }

    return result


def main():
    parser = argparse.ArgumentParser(description="PPT 性能优化器(分批并行生成)")
    parser.add_argument("--content", required=True, help="内容 JSON 文件路径")
    parser.add_argument("--batch-size", type=int, default=5, help="每批页数(默认5)")
    parser.add_argument("--workers", type=int, default=None, help="并行进程数(默认CPU-1)")
    parser.add_argument("--output", help="输出 PPTX 文件路径")
    args = parser.parse_args()

    if not Path(args.content).exists():
        print(f"错误: 文件不存在 - {args.content}")
        sys.exit(1)

    result = optimize_generation(
        args.content,
        batch_size=args.batch_size,
        workers=args.workers,
        output_path=args.output,
    )
    output_json = json.dumps(result, ensure_ascii=False, indent=2)
    print(output_json)


if __name__ == "__main__":
    main()