# AI生成
#!/usr/bin/env python3
"""
演讲备注生成器(v2.0)
支持三种工作模式:
  1. --extract    提取每页内容到JSON,供Agent阅读后手写高质量备注
  2. --inject     将Agent写好的备注JSON注入PPTX
  3. --style      规则兜底模式(改进版,无外部依赖时使用)

v2.0 改进要点:
  - 新增 extract/inject 两阶段工作流,支持Agent理解内容后手写备注
  - 规则模式重写:去除"这一点需要特别注意"等机械模板
  - 内容提取增强:识别标题层级、数据类型、图表描述、要点分组
  - 新增受众/场景参数,备注风格更贴合实际用途
"""

import argparse
import json
import re
import sys
from pathlib import Path

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


# ============================================================
# 阶段一:内容提取(供Agent阅读理解)
# ============================================================

def extract_slide_content(slide, slide_idx, total_slides):
    """提取幻灯片全部内容,输出结构化JSON供Agent理解"""
    title = ""
    subtitle = ""
    body_texts = []
    all_texts = []
    has_chart = False
    has_image = False
    has_table = False
    data_items = []
    chart_info = []
    image_count = 0
    shape_count = 0

    for shape in slide.shapes:
        shape_count += 1

        # 检测图表
        if shape.has_chart:
            has_chart = True
            chart = shape.chart
            chart_type = str(chart.chart_type) if hasattr(chart, 'chart_type') else "unknown"
            series_names = []
            for series in chart.series:
                s_name = series.name if hasattr(series, 'name') and series.name else f"series_{len(series_names)+1}"
                series_names.append(s_name)
                try:
                    for point in series.points:
                        if point is not None:
                            val = str(point)
                            data_items.append(val)
                except Exception:
                    pass
            chart_info.append({
                "type": chart_type,
                "series": series_names,
            })

        # 检测图片
        if shape.shape_type == 13:  # Picture
            has_image = True
            image_count += 1

        # 检测表格
        if shape.has_table:
            has_table = True
            table = shape.table
            table_data = []
            for row in table.rows:
                row_data = [cell.text.strip() for cell in row.cells]
                table_data.append(row_data)
            body_texts.append(f"[表格] {json.dumps(table_data, ensure_ascii=False)}")

        # 提取文本
        if shape.has_text_frame:
            for para in shape.text_frame.paragraphs:
                text = para.text.strip()
                if not text:
                    continue
                all_texts.append(text)

                # 识别标题(第一个文本框的第一段通常是大标题)
                if not title and shape == slide.shapes[0]:
                    title = text
                elif not subtitle and shape == slide.shapes[0] and para != shape.text_frame.paragraphs[0]:
                    subtitle = text
                else:
                    body_texts.append(text)

                # 检测数字数据(百分比、绝对值、比率)
                numbers = re.findall(r'-?\d+\.?\d*%?', text)
                for num in numbers:
                    if len(num) > 1:  # 过滤单字符
                        data_items.append(num)

    # 去重数据
    unique_data = list(dict.fromkeys(data_items))

    return {
        "slide_index": slide_idx + 1,
        "total_slides": total_slides,
        "is_first": slide_idx == 0,
        "is_last": slide_idx == total_slides - 1,
        "title": title or f"第{slide_idx + 1}页",
        "subtitle": subtitle,
        "body_texts": body_texts,
        "all_texts": all_texts,
        "data_items": unique_data[:20],  # 限制数量
        "has_chart": has_chart,
        "chart_info": chart_info,
        "has_image": has_image,
        "image_count": image_count,
        "has_table": has_table,
        "shape_count": shape_count,
    }


def extract_all_slides(pptx_path, output_path=None):
    """提取所有幻灯片内容到JSON"""
    if not HAS_PPTX:
        return {"error": "python-pptx not installed. Run: pip install python-pptx"}

    prs = Presentation(pptx_path)
    total_slides = len(prs.slides)
    slides_content = []

    for i, slide in enumerate(prs.slides):
        content = extract_slide_content(slide, i, total_slides)
        slides_content.append(content)

    result = {
        "source_file": str(pptx_path),
        "total_slides": total_slides,
        "slides": slides_content,
        "instruction": (
            "以上是PPT每页的结构化内容。请逐页阅读理解后,为每页撰写高质量演讲备注。"
            "备注要求:1)开场过渡承上启下 2)核心内容解读(不照念,要展开分析)"
            "3)关键数据引用并给出含义 4)结尾过渡引出下一页主题。"
            "输出JSON格式:{\"notes\": [{\"slide\": 1, \"text\": \"备注全文\"}, ...]}"
        ),
    }

    if output_path:
        Path(output_path).write_text(
            json.dumps(result, ensure_ascii=False, indent=2),
            encoding="utf-8"
        )
        result["output_file"] = output_path

    return result


# ============================================================
# 阶段二:备注注入(将Agent写好的备注写入PPTX)
# ============================================================

def inject_notes(pptx_path, notes_json_path, output_path=None):
    """从JSON文件读取备注并注入PPTX"""
    if not HAS_PPTX:
        return {"error": "python-pptx not installed. Run: pip install python-pptx"}

    # 读取备注JSON
    notes_data = json.loads(
        Path(notes_json_path).read_text(encoding="utf-8")
    )

    # 兼容多种JSON格式
    notes_list = notes_data.get("notes", notes_data) if isinstance(notes_data, dict) else notes_data

    # 构建slide→text映射
    notes_map = {}
    for item in notes_list:
        if isinstance(item, dict):
            slide_num = item.get("slide") or item.get("slide_index") or item.get("page")
            text = item.get("text") or item.get("notes") or item.get("content") or ""
            if slide_num and text:
                notes_map[int(slide_num)] = text

    prs = Presentation(pptx_path)
    total_slides = len(prs.slides)
    injected = []

    for i, slide in enumerate(prs.slides):
        slide_num = i + 1
        if slide_num in notes_map:
            notes_text = notes_map[slide_num]
            notes_slide = slide.notes_slide
            notes_slide.notes_text_frame.text = notes_text
            injected.append({
                "slide": slide_num,
                "status": "injected",
                "length": len(notes_text),
                "preview": notes_text[:120] + "..." if len(notes_text) > 120 else notes_text,
            })
        else:
            injected.append({
                "slide": slide_num,
                "status": "skipped (no note provided)",
            })

    # 保存
    if not output_path:
        stem = Path(pptx_path).stem
        suffix = Path(pptx_path).suffix
        output_path = str(Path(pptx_path).parent / f"{stem}_with_notes{suffix}")

    prs.save(output_path)

    return {
        "total_slides": total_slides,
        "notes_injected": sum(1 for x in injected if x["status"] == "injected"),
        "notes_skipped": sum(1 for x in injected if "skipped" in x["status"]),
        "output_file": output_path,
        "details": injected,
    }


# ============================================================
# 阶三:规则兜底模式(改进版,无Agent介入时使用)
# ============================================================

def _classify_content(content):
    """分析内容类型,辅助生成更有针对性的备注"""
    texts = " ".join(content.get("all_texts", []))
    has_chart = content.get("has_chart", False)
    has_table = content.get("has_table", False)
    data_items = content.get("data_items", [])

    # 检测内容类型
    if any(kw in texts for kw in ["总结", "结论", "谢谢", "感谢", "Thank"]):
        return "closing"
    if any(kw in texts for kw in ["封面", "目录", "大纲", "议程", "Agenda"]):
        return "cover"
    if has_chart and len(data_items) > 3:
        return "data_heavy"
    if has_table:
        return "comparison"
    if any(kw in texts for kw in ["vs", "对比", "比较", "差异"]):
        return "comparison"
    if any(kw in texts for kw in ["趋势", "增长", "下降", "变化"]):
        return "trend"
    return "general"


def _format_data_items(data_items, max_count=5):
    """格式化数据项,使其在备注中更自然"""
    if not data_items:
        return ""
    items = data_items[:max_count]
    if len(items) == 1:
        return items[0]
    elif len(items) == 2:
        return f"{items[0]}和{items[1]}"
    else:
        return "、".join(items[:-1]) + f"及{items[-1]}"


def generate_notes_rule(content, style="formal", slide_context=None):
    """
    规则兜底生成备注(v2.0改进版)
    改进:去除机械模板,根据内容类型差异化生成,数据引用更自然
    """
    title = content["title"]
    body_texts = content["body_texts"]
    data_items = content["data_items"]
    is_first = content.get("is_first", False)
    is_last = content.get("is_last", False)
    content_type = _classify_content(content)

    # 风格参数
    style_cfg = {
        "formal": {"prefix": "", "tone_sep": "。", "close": "接下来", "ending": "以上是本次分享的全部内容,感谢各位的关注。"},
        "casual": {"prefix": "好,", "tone_sep": "。", "close": "下面", "ending": "今天就聊到这儿,谢谢大家!"},
        "energetic": {"prefix": "", "tone_sep": "!", "close": "现在", "ending": "这就是今天的全部内容!感谢大家的聆听!"},
    }
    cfg = style_cfg.get(style, style_cfg["formal"])

    parts = []

    # 1. 开场过渡 — 根据内容类型差异化
    if is_first:
        if content_type == "cover":
            parts.append(f"各位好,欢迎参加本次分享。今天我们将围绕{title}展开分析。")
        else:
            parts.append(f"各位好,今天我们首先来看{title}{cfg['tone_sep']}")
    elif content_type == "closing":
        parts.append(f"最后,我们来做一个总结{cfg['tone_sep']}")
    elif content_type == "data_heavy":
        parts.append(f"这一页是关键数据页,请重点关注{title}的核心数字{cfg['tone_sep']}")
    elif content_type == "comparison":
        parts.append(f"这一页通过对比来揭示{title}的差异{cfg['tone_sep']}")
    elif content_type == "trend":
        parts.append(f"这一页展示{title}的变化趋势{cfg['tone_sep']}")
    else:
        parts.append(f"{cfg['prefix']}接下来看{title}{cfg['tone_sep']}")

    # 2. 要点展开 — 改进:不套固定模板,而是概括性展开
    if body_texts:
        meaningful_texts = [t for t in body_texts if len(t) > 2 and t not in title]
        if meaningful_texts:
            if len(meaningful_texts) <= 2:
                # 少量要点:直接展开
                for text in meaningful_texts:
                    clean = text[:100]  # 限制长度
                    parts.append(f"  {clean}{cfg['tone_sep']}")
            else:
                # 多要点:概括前2个,提示还有更多
                parts.append(f"  本页包含{len(meaningful_texts)}个要点,核心包括:")
                for text in meaningful_texts[:3]:
                    clean = text[:80]
                    parts.append(f"  · {clean}{cfg['tone_sep']}")
                if len(meaningful_texts) > 3:
                    parts.append(f"  此外还有{len(meaningful_texts) - 3}个支撑性论点{cfg['tone_sep']}")

    # 3. 数据强调 — 改进:自然引用而非模板套用
    if data_items:
        data_str = _format_data_items(data_items, 5)
        if content_type == "data_heavy":
            parts.append(f"  关键数据:{data_str},这些数字直接反映了当前市场状况{cfg['tone_sep']}")
        elif content_type == "trend":
            parts.append(f"  数据变化:{data_str},趋势已经非常明确{cfg['tone_sep']}")
        else:
            parts.append(f"  其中涉及的关键数据有:{data_str}{cfg['tone_sep']}")

    # 4. 图表/表格提示
    if content.get("has_chart"):
        chart_types = [c["type"] for c in content.get("chart_info", [])]
        parts.append(f"  请结合图表({'、'.join(chart_types)})直观理解上述内容{cfg['tone_sep']}")
    if content.get("has_table"):
        parts.append(f"  表格中的数据对比值得仔细关注{cfg['tone_sep']}")

    # 5. 结尾过渡 — 改进:不套固定模板
    if is_last:
        parts.append(cfg["ending"])
    elif content_type == "closing":
        parts.append("欢迎各位就感兴趣的话题进一步交流。")
    else:
        parts.append(f"{cfg['close']}进入下一页的分析{cfg['tone_sep']}")

    return "\n".join(parts)


def process_pptx_rule(pptx_path, style="formal", output_path=None):
    """规则兜底模式:自动生成备注(改进版)"""
    if not HAS_PPTX:
        return {"error": "python-pptx not installed. Run: pip install python-pptx"}

    prs = Presentation(pptx_path)
    total_slides = len(prs.slides)
    notes_generated = []

    for i, slide in enumerate(prs.slides):
        content = extract_slide_content(slide, i, total_slides)
        notes_text = generate_notes_rule(content, style=style)

        notes_slide = slide.notes_slide
        notes_slide.notes_text_frame.text = notes_text

        notes_generated.append({
            "slide": i + 1,
            "title": content["title"],
            "content_type": _classify_content(content),
            "notes_preview": notes_text[:120] + "..." if len(notes_text) > 120 else notes_text,
        })

    if not output_path:
        stem = Path(pptx_path).stem
        suffix = Path(pptx_path).suffix
        output_path = str(Path(pptx_path).parent / f"{stem}_with_notes{suffix}")

    prs.save(output_path)

    return {
        "mode": "rule_based_v2",
        "total_slides": total_slides,
        "style": style,
        "notes_generated": len(notes_generated),
        "output_file": output_path,
        "details": notes_generated,
    }


# ============================================================
# 主入口
# ============================================================

def main():
    parser = argparse.ArgumentParser(description="演讲备注生成器 v2.0")
    parser.add_argument("--input", required=True, help="输入 PPTX 文件路径")
    parser.add_argument("--output", help="输出文件路径")
    parser.add_argument("--style", choices=["formal", "casual", "energetic"],
                        default="formal", help="演讲风格(规则模式)")
    parser.add_argument("--extract", action="store_true",
                        help="阶段一:提取每页内容到JSON,供Agent阅读")
    parser.add_argument("--inject", action="store_true",
                        help="阶段二:将Agent备注JSON注入PPTX")
    parser.add_argument("--notes-json", help="Agent写好的备注JSON文件路径(--inject模式使用)")
    args = parser.parse_args()

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

    # 阶段一:提取内容
    if args.extract:
        output = args.output or str(Path(args.input).with_suffix(".content.json"))
        result = extract_all_slides(args.input, output)
        print(json.dumps(result, ensure_ascii=False, indent=2))
        return

    # 阶段二:注入备注
    if args.inject:
        if not args.notes_json:
            print("错误: --inject 模式需要 --notes-json 参数")
            sys.exit(1)
        if not Path(args.notes_json).exists():
            print(f"错误: 备注文件不存在 - {args.notes_json}")
            sys.exit(1)
        result = inject_notes(args.input, args.notes_json, args.output)
        print(json.dumps(result, ensure_ascii=False, indent=2))
        return

    # 默认:规则兜底模式
    result = process_pptx_rule(args.input, style=args.style, output_path=args.output)
    print(json.dumps(result, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()