"""
JoySpace 趋势图生成（借鉴 trend-chart-generator skill）。

能力：
- chart.generate_trend: 生成标准同比趋势图(3条线: 预算目标/26年实际同比率/25年实际同比率)
  支持 null 值线段截断、合并月规则、跨平台中文字体、图片base64嵌入JoySpace content JSON

移植自 trend-chart-generator skill 的 generate_trend_chart.py (710行),
封装为 joyspace-pro 的 action。原脚本在 utils/generate_trend_chart.py。
"""

import json
import os
import sys
from pathlib import Path

# 导入趋势图生成核心(在utils目录)
_here = Path(__file__).resolve().parent
_utils = _here.parent / "utils"
if str(_utils) not in sys.path:
    sys.path.insert(0, str(_utils))


def generate_trend(client, params: dict) -> dict:
    """生成标准同比趋势图(借鉴trend-chart-generator)。

    params:
        title: 图表标题(如"省区销售签约收入同比趋势")
        target: 目标值列表(逗号分隔或数组, null表示缺失)
        yoy26: 26年同比率列表(逗号分隔或数组)
        yoy25: 25年同比率列表(逗号分隔或数组)
        output: 输出PNG路径(默认 trend_chart.png)
        months: X轴标签(逗号分隔, 默认1-10月)
        legend_target/legend_yoy26/legend_yoy25: 图例名称(可选)
        color_target/color_yoy26/color_yoy25: 线条颜色(可选)
        joyspace_json: 若提供, 将PNG转base64嵌入JoySpace content JSON输出到此路径
    """
    try:
        from generate_trend_chart import generate_chart
    except ImportError as e:
        raise RuntimeError(f"导入趋势图生成器失败(需matplotlib): {e}")

    title = params.get("title", "同比趋势")
    output = params.get("output", "trend_chart.png")

    # 解析数值列表(支持逗号分隔字符串或数组, 支持null)
    def _parse_values(v):
        if v is None:
            return []
        if isinstance(v, str):
            return [None if x.strip().lower() == "null" else float(x.strip())
                    for x in v.split(",") if x.strip()]
        return [None if x is None else float(x) for x in v]

    target_values = _parse_values(params.get("target"))
    yoy26_values = _parse_values(params.get("yoy26"))
    yoy25_values = _parse_values(params.get("yoy25"))

    months = params.get("months")
    if isinstance(months, str):
        months = [m.strip() for m in months.split(",")]
    elif months is None:
        months = [str(i) for i in range(1, len(yoy26_values) + 1)] if yoy26_values else None

    legend_names = {}
    if params.get("legend_target"): legend_names["target"] = params["legend_target"]
    if params.get("legend_yoy26"): legend_names["yoy26"] = params["legend_yoy26"]
    if params.get("legend_yoy25"): legend_names["yoy25"] = params["legend_yoy25"]

    colors = {}
    if params.get("color_target"): colors["target"] = params["color_target"]
    if params.get("color_yoy26"): colors["yoy26"] = params["color_yoy26"]
    if params.get("color_yoy25"): colors["yoy25"] = params["color_yoy25"]

    print(f"[趋势图] 标题={title}")
    print(f"  target({len(target_values)}): {target_values}")
    print(f"  yoy26({len(yoy26_values)}): {yoy26_values}")
    print(f"  yoy25({len(yoy25_values)}): {yoy25_values}")

    # 生成图表
    generate_chart(
        title=title,
        target_values=target_values,
        yoy_26_values=yoy26_values,
        yoy_25_values=yoy25_values,
        output_path=output,
        months=months,
        legend_names=legend_names if legend_names else None,
        colors=colors if colors else None,
    )
    print(f"  ✓ PNG生成: {output} ({os.path.getsize(output)/1024:.1f}KB)")

    # 可选: 生成JoySpace content JSON(图片base64嵌入)
    joyspace_json_path = params.get("joyspace_json")
    if joyspace_json_path:
        try:
            # 调用原脚本的joyspace-json转换逻辑
            from generate_trend_chart import _gen_id, _read_image_pixels, _parse_rich_text
            import base64
            with open(output, "rb") as f:
                img_b64 = base64.b64encode(f.read()).decode()
            # 构造content JSON(图片作为image block, base64嵌入)
            content_json = [{
                "id": _gen_id(),
                "name": "趋势图",
                "type": "image",
                "attributes": {"image": {"url": f"data:image/png;base64,{img_b64}"}},
            }]
            with open(joyspace_json_path, "w", encoding="utf-8") as f:
                json.dump(content_json, f, ensure_ascii=False)
            print(f"  ✓ JoySpace content JSON: {joyspace_json_path}")
        except Exception as e:
            print(f"  [WARN] joyspace-json生成失败(图片仍已生成): {e}")

    return {
        "output": output,
        "size": os.path.getsize(output),
        "target_count": len(target_values),
        "yoy26_count": len(yoy26_values),
        "yoy25_count": len(yoy25_values),
        "joyspace_json": joyspace_json_path if joyspace_json_path else None,
    }
