#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
标准趋势图生成器
- 3条线：26年预算目标（藏蓝实线 #1E3C5A）、26年实际同比率（红色实线 #E00000）、25年实际同比率（灰色实线 #999999）
- 平滑曲线（三次样条插值）
- 每个数据点标注 X.X% 标签（1位小数）
- 仅横轴，无纵轴数字，无网格线，无背景框
- 图例在右侧
- 支持 null 值：数据为空时线段截止不延伸
"""

# FINBOX_MONITOR_AUTOLOAD_START
try:
    from pathlib import Path as _finbox_monitor_path
    import sys as _finbox_monitor_sys

    _finbox_current = _finbox_monitor_path(__file__).resolve()
    for _finbox_parent in (_finbox_current.parent, *_finbox_current.parents):
        _finbox_monitor_dir = _finbox_parent / "skill_monitor"
        if (_finbox_monitor_dir / "monitor_guard.py").exists():
            _finbox_monitor_sys.path.insert(0, str(_finbox_monitor_dir))
            try:
                from monitor_guard import autoload as _finbox_monitor_autoload

                _finbox_monitor_autoload()
            finally:
                try:
                    _finbox_monitor_sys.path.remove(str(_finbox_monitor_dir))
                except ValueError:
                    pass
            break
except Exception:
    pass
# FINBOX_MONITOR_AUTOLOAD_END

import argparse
import json
import os
import sys

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import make_interp_spline

# ── 默认样式 ──────────────────────────────────────────────
DEFAULT_COLORS = {
    "target": "#1E3C5A",
    "yoy_26": "#E00000",
    "yoy_25": "#999999",
}

DEFAULT_LEGEND_NAMES = {
    "target": "26年预算目标",
    "yoy_26": "26年实际同比率",
    "yoy_25": "25年实际同比率",
}

DEFAULT_MONTHS = ["1-2月", "3月", "4月", "5-6月", "7月", "8月",
                  "9月", "10月", "11月", "12月"]


# ── 工具函数 ──────────────────────────────────────────────
def _clean_values(raw):
    """将列表中的 null/None/空字符串转为 None，其余转 float"""
    result = []
    for v in raw:
        if v is None or v == "null" or v == "" or v == "None":
            result.append(None)
        else:
            try:
                result.append(float(v))
            except (ValueError, TypeError):
                result.append(None)
    return result


def _truncate_at_null(values, months):
    """
    从第一个 None 出现的位置截断，只保留前面有数据的部分。
    返回 (有效值列表, 有效月份列表, 起始索引, 截断后索引列表)
    """
    first_null = None
    for i, v in enumerate(values):
        if v is None:
            first_null = i
            break

    if first_null is None:
        return values, months, 0, list(range(len(values)))

    # 只取到第一个 None 之前的数据
    return values[:first_null], months[:first_null], 0, list(range(first_null))


def _smooth_curve(x_arr, y_arr, num_points=300):
    """三次样条平滑插值，至少需要4个点才能做 k=3"""
    if len(x_arr) < 4:
        # 点太少无法做三次样条，退回 k=2 或 k=1
        k = min(len(x_arr) - 1, 3)
        if k < 1:
            return x_arr, y_arr
        spl = make_interp_spline(x_arr, y_arr, k=k)
    else:
        spl = make_interp_spline(x_arr, y_arr, k=3)

    x_smooth = np.linspace(x_arr.min(), x_arr.max(), num_points)
    return x_smooth, spl(x_smooth)


def _auto_label_offset(y_vals, direction="above"):
    """
    根据线的走势自动决定标签偏移方向，避免重叠。
    direction: "above" 或 "below" 的默认偏好
    """
    return (0, 10) if direction == "above" else (0, -14)


def _get_chinese_fonts():
    """跨平台中文字体检测：返回当前系统可用的中文字体列表。"""
    import platform
    system = platform.system()  # 'Windows', 'Darwin'(macOS/iOS), 'Linux'

    # 各平台候选字体（按优先级排列）
    candidates = {
        "Windows": ["Microsoft YaHei", "SimHei", "SimSun", "FangSong"],
        "Darwin": ["PingFang SC", "Heiti SC", "STHeiti", "Hiragino Sans GB", "Arial Unicode MS"],
        "Linux": ["WenQuanYi Micro Hei", "WenQuanYi Zen Hei", "Noto Sans CJK SC", "Droid Sans Fallback"],
    }

    # 获取 matplotlib 已注册的字体名
    from matplotlib.font_manager import fontManager
    available = {f.name for f in fontManager.ttflist}

    # 按平台候选顺序，筛选出实际可用的
    platform_fonts = candidates.get(system, candidates["Linux"])
    matched = [f for f in platform_fonts if f in available]

    if matched:
        return matched

    # 兜底：尝试所有平台的候选字体
    all_candidates = []
    for fonts in candidates.values():
        all_candidates.extend(fonts)
    fallback_matched = [f for f in all_candidates if f in available]

    if fallback_matched:
        return fallback_matched

    # 最终兜底：sans-serif（matplotlib 默认），中文可能显示为方块
    return ["sans-serif"]


# ── 主绘制函数 ─────────────────────────────────────────────
def generate_chart(
    title: str,
    target_values: list,
    yoy_26_values: list,
    yoy_25_values: list,
    output_path: str = "trend_chart.png",
    months: list = None,
    legend_names: dict = None,
    colors: dict = None,
    figsize: tuple = (14, 5.2),
    dpi: int = 150,
):
    """
    生成标准趋势图。

    Parameters
    ----------
    title : 图表标题（如"省区销售签约收入同比趋势"）
    target_values : 10个值，null 表示无数据
    yoy_26_values : 10个值，null 表示无数据
    yoy_25_values : 10个值，null 表示无数据
    output_path : 输出 PNG 文件路径
    months : X轴标签，默认 ["1-2月","3月",...,"12月"]
    legend_names : 自定义图例名称 {"target":..., "yoy_26":..., "yoy_25":...}
    colors : 自定义颜色 {"target":..., "yoy_26":..., "yoy_25":...}
    figsize : 画布尺寸
    dpi : 分辨率
    """
    # ── 参数补全 ──
    if months is None:
        months = DEFAULT_MONTHS[:]
    _colors = {**DEFAULT_COLORS, **(colors or {})}
    _legends = {**DEFAULT_LEGEND_NAMES, **(legend_names or {})}

    target_values = _clean_values(target_values)
    yoy_26_values = _clean_values(yoy_26_values)
    yoy_25_values = _clean_values(yoy_25_values)

    n = len(months)
    x_all = np.arange(n)

    # ── 画布 + 跨平台字体 ──
    chinese_fonts = _get_chinese_fonts()
    plt.rcParams['font.sans-serif'] = chinese_fonts
    plt.rcParams['axes.unicode_minus'] = False

    fig, ax = plt.subplots(figsize=figsize)
    fig.patch.set_facecolor('white')
    ax.set_facecolor('white')

    # ── 绘制每条线 ──
    lines_config = [
        ("target", target_values, _colors["target"], 1.8, _legends["target"], "above"),
        ("yoy_26", yoy_26_values, _colors["yoy_26"], 2.2, _legends["yoy_26"], "above"),
        ("yoy_25", yoy_25_values, _colors["yoy_25"], 2.2, _legends["yoy_25"], "below"),
    ]

    for key, values, color, lw, legend_name, label_dir in lines_config:
        # 截断到第一个 None
        eff_vals, eff_months, _, eff_x_idx = _truncate_at_null(values, months)

        if len(eff_vals) < 2:
            # 至少需要2个点才能画线
            if len(eff_vals) == 1:
                # 单点：只标数据标签
                ax.annotate(f'{eff_vals[0]:.1f}%', (eff_x_idx[0], eff_vals[0]),
                            textcoords='offset points',
                            xytext=_auto_label_offset(eff_vals, label_dir),
                            ha='center', fontsize=8.5, color=color, fontweight='medium')
            continue

        eff_x = np.array(eff_x_idx, dtype=float)

        # 平滑曲线
        x_smooth, y_smooth = _smooth_curve(eff_x, np.array(eff_vals))

        # 画线
        ax.plot(x_smooth, y_smooth, color=color, linewidth=lw, linestyle='-',
                label=legend_name, zorder=2 if key == "target" else 3)

        # 数据标签（只在实际数据点位置标注）
        for i, (xi, yi) in enumerate(zip(eff_x, eff_vals)):
            offset = _auto_label_offset(eff_vals, label_dir)
            ax.annotate(f'{yi:.1f}%', (xi, yi),
                        textcoords='offset points', xytext=offset,
                        ha='center', fontsize=8.5, color=color, fontweight='medium')

    # ── 样式 ──
    ax.grid(False)

    # 隐藏所有轴线，只保留月份文字
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.spines['bottom'].set_visible(False)

    # X 轴标签（只有文字，无线）
    ax.set_xticks(x_all)
    ax.set_xticklabels(months, fontsize=11, color='#333333')
    ax.tick_params(axis='x', length=0, colors='#333333', pad=8)

    # 无 Y 轴刻度
    ax.tick_params(axis='y', left=False, labelleft=False)

    # 标题
    ax.set_title(title, fontsize=14, fontweight='bold',
                 color='#333333', pad=15, loc='center')

    # 图例在右侧
    ax.legend(loc='center left', bbox_to_anchor=(1.01, 0.5),
              frameon=False, fontsize=11,
              handlelength=2.5, handletextpad=0.5, borderpad=0.5)

    plt.tight_layout()
    plt.subplots_adjust(right=0.82)

    # ── 保存 ──
    out_dir = os.path.dirname(os.path.abspath(output_path))
    os.makedirs(out_dir, exist_ok=True)

    fig.savefig(output_path, dpi=dpi, bbox_inches='tight',
                facecolor='white', edgecolor='none')
    plt.close(fig)

    abs_path = os.path.abspath(output_path)
    print(f"[OK] 趋势图已生成: {abs_path}")
    print(f"[MD] 插入语法: ![{title}](./{os.path.basename(output_path)})")
    return abs_path


# ── JoySpace content JSON 辅助 ──────────────────────────────
def _gen_id(length: int = 6) -> str:
    """生成 JoySpace 节点需要的随机 id（6位字母数字）"""
    import random, string
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))


def _read_image_pixels(img_bytes: bytes, ext: str = "png"):
    """从图片二进制数据中读取像素尺寸（width, height）。
    支持 PNG（IHDR 头）和 JPEG（SOF0 标记）。
    返回 (width, height) 或 (None, None)。
    """
    import struct
    try:
        if ext == "png":
            # PNG signature: 89 50 4E 47 0D 0A 1A 0A
            png_sig = b'\x89PNG\r\n\x1a\n'
            if len(img_bytes) > 24 and img_bytes[:8] == png_sig:
                w = struct.unpack('>I', img_bytes[16:20])[0]
                h = struct.unpack('>I', img_bytes[20:24])[0]
                return w, h
        elif ext in ("jpg", "jpeg"):
            # JPEG SOF0 marker: FF C0 xx xx height(2B) width(2B)
            i = 2  # skip SOI
            while i < len(img_bytes) - 1:
                if img_bytes[i] != 0xFF:
                    break
                marker = img_bytes[i + 1]
                if marker in (0xC0, 0xC1, 0xC2):  # SOF0, SOF1, SOF2
                    h = struct.unpack('>H', img_bytes[i+5:i+7])[0]
                    w = struct.unpack('>H', img_bytes[i+7:i+9])[0]
                    return w, h
                elif marker == 0xD9:  # EOI
                    break
                elif marker in (0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0x01):
                    i += 2  # no length field
                else:
                    length = struct.unpack('>H', img_bytes[i+2:i+4])[0]
                    i += 2 + length
    except Exception:
        pass
    return None, None


def _parse_rich_text(text: str) -> list:
    """
    将含 HTML 颜色标签和 Markdown 格式的文本转为 JoySpace rich children。
    - <span style="color:red">xxx</span> → {"text": "xxx", "fontColor": "#E00000"}
    - <font color="red">xxx</font> → {"text": "xxx", "fontColor": "#E00000"}
    - **加粗** → {"text": "加粗", "bold": True}
    普通文本 → {"text": "..."}
    """
    import re
    children = []

    # 先处理 **加粗** → 临时标记，避免与颜色标签冲突
    # 用 Unicode 私有区字符 U+E001 / U+E002 包裹加粗文本作为中间态
    _BOLD_OPEN = ''
    _BOLD_CLOSE = ''
    temp = text.replace('**', _BOLD_OPEN, 1)
    while _BOLD_OPEN in temp:
        # 交替替换：奇数次替换为 OPEN，偶数次替换为 CLOSE
        temp = re.sub(r'\*\*(.+?)\*\*', _BOLD_OPEN + r'\1' + _BOLD_CLOSE, temp)

    # 统一匹配所有颜色标签：<span style="color:red"> 或 <font color="red">
    # 支持 color 值为 red、#E00000、rgb(224,0,0) 等写法
    color_pattern = re.compile(
        r'<(?:span\s+style="color:\s*(red|#E00000|#e00000|rgb\(224,\s*0,\s*0\))"|'
        r'font\s+color="(?:red|#E00000|#e00000)")\s*>(.*?)</(?:span|font)>',
        re.IGNORECASE
    )

    last_end = 0
    for m in color_pattern.finditer(temp):
        # 前面的文本（可能含加粗标记）
        if m.start() > last_end:
            plain = temp[last_end:m.start()]
            if plain:
                children.extend(_split_bold_markers(plain, font_color=None))
        # 红色文本（可能含加粗标记）
        children.extend(_split_bold_markers(m.group(2), font_color="#E00000"))
        last_end = m.end()

    # 尾部文本
    if last_end < len(temp):
        remaining = temp[last_end:]
        if remaining:
            children.extend(_split_bold_markers(remaining, font_color=None))

    # 兜底：没有任何匹配的情况
    if not children:
        children.extend(_split_bold_markers(temp, font_color=None))

    # 过滤空文本节点
    children = [c for c in children if c.get("text")]

    return children


def _split_bold_markers(text: str, font_color: str = None) -> list:
    """
    将含加粗标记的文本拆分为 JoySpace rich children。
    每个 child 可带 fontColor 和 bold 属性。
    加粗标记使用 Unicode 私有区字符 U+E001 / U+E002。
    """
    import re
    _BOLD_OPEN = ''
    _BOLD_CLOSE = ''
    result = []

    # 用标记拆分
    # 模式：普通文本 <OPEN> 加粗文本 <CLOSE> 普通文本 ...
    pattern = re.compile(re.escape(_BOLD_OPEN) + r'(.*?)' + re.escape(_BOLD_CLOSE))
    last_end = 0
    for m in pattern.finditer(text):
        # 前面的普通文本
        if m.start() > last_end:
            plain = text[last_end:m.start()]
            if plain:
                child = {"text": plain}
                if font_color:
                    child["fontColor"] = font_color
                result.append(child)
        # 加粗文本
        child = {"text": m.group(1), "bold": True}
        if font_color:
            child["fontColor"] = font_color
        result.append(child)
        last_end = m.end()

    # 尾部文本
    if last_end < len(text):
        remaining = text[last_end:]
        if remaining:
            child = {"text": remaining}
            if font_color:
                child["fontColor"] = font_color
            result.append(child)

    # 兜底：没有标记
    if not result:
        child = {"text": text}
        if font_color:
            child["fontColor"] = font_color
        result.append(child)

    return result


def _md_table_to_joyspace_table(table_lines: list) -> dict:
    """
    将 Markdown 表格行列表转为 JoySpace 原生 table 节点。
    自动过滤分隔行（|---|---|），生成 table-row / table-cell。
    每个节点带随机 id。
    """
    import re

    # 解析每行
    parsed_rows = []
    for line in table_lines:
        # 去掉首尾 |
        inner = line.strip()
        if inner.startswith("|"):
            inner = inner[1:]
        if inner.endswith("|"):
            inner = inner[:-1]
        cells = [c.strip() for c in inner.split("|")]
        # 检测分隔行（全是 -、:、空格组成）
        is_separator = all(re.match(r'^[-: ]+$', c) for c in cells if c)
        if not is_separator:
            parsed_rows.append(cells)

    if not parsed_rows:
        return None

    # 确定列数（取最大值）
    num_cols = max(len(row) for row in parsed_rows)
    # 补齐短行
    for row in parsed_rows:
        while len(row) < num_cols:
            row.append("")

    # 列宽：等宽分配，每列 120
    col_width = 120
    width = [col_width] * num_cols

    # 计算 height: 行数 * 34 (大约)
    height = len(parsed_rows) * 34

    # 构建 JoySpace table 节点（每个节点带 id）
    table_children = []
    for row in parsed_rows:
        row_children = []
        for cell_text in row:
            cell_children = [{"type": "p", "id": _gen_id(), "children": _parse_rich_text(cell_text)}]
            row_children.append({"type": "table-cell", "id": _gen_id(), "children": cell_children})
        table_children.append({"type": "table-row", "id": _gen_id(), "children": row_children})

    table_node = {
        "type": "table",
        "id": _gen_id(),
        "width": width,
        "height": height,
        "children": table_children,
    }
    return table_node


def md_to_joyspace_json(md_text: str, img_dir: str = None) -> list:
    """
    将 Markdown 文本转为 JoySpace content JSON 格式。
    - 表格 → JoySpace 原生 table 节点（table-row / table-cell）
    - 图片 → base64 嵌入的 img 节点
    - 标题 → h1~h6
    - 列表项（- 开头）→ 扁平 list 节点（value: "bullet", indent: 0）
    - 分割线（---）→ divider
    - <span style="color:red"> / <font color="red"> → rich text with color 属性
    - **加粗** → rich text with bold 属性
    每个节点带随机 id，符合 JoySpace Slate 编辑器要求。
    img_dir: 图片文件所在的目录，默认为当前目录。
    """
    import base64
    import re

    if img_dir is None:
        img_dir = "."

    # 去除 BOM 字符（﻿），避免标题识别失败
    md_text = md_text.lstrip("﻿")

    nodes = []
    lines = md_text.split("\n")
    i = 0

    while i < len(lines):
        line = lines[i]
        stripped = line.strip()

        # 空行跳过
        if not stripped:
            i += 1
            continue

        # 图片 ![alt](path)
        img_match = re.match(r'!\[([^\]]*)\]\(([^)]+)\)', stripped)
        if img_match:
            img_path = img_match.group(2)
            # 读取本地图片并 base64 编码
            full_img_path = os.path.join(img_dir, img_path)
            if os.path.isfile(full_img_path):
                with open(full_img_path, "rb") as f:
                    img_bytes = f.read()
                img_b64 = base64.b64encode(img_bytes).decode()
                ext = os.path.splitext(full_img_path)[1].lower()
                mime = {"png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg"}.get(ext.lstrip("."), "image/png")

                # 读取 PNG/JPEG 像素尺寸，写入 JoySpace img 节点
                img_w, img_h = _read_image_pixels(img_bytes, ext.lstrip("."))
                img_node = {"type": "img", "id": _gen_id(),
                            "url": f"data:{mime};base64,{img_b64}",
                            "children": [{"text": ""}]}
                if img_w and img_h:
                    img_node["width"] = img_w
                    img_node["height"] = img_h
                nodes.append(img_node)
            else:
                nodes.append({"type": "img", "id": _gen_id(), "url": img_path, "children": [{"text": ""}]})
            i += 1
            continue

        # 标题
        heading_match = re.match(r'^(#{1,6})\s+(.*)', stripped)
        if heading_match:
            level = len(heading_match.group(1))
            text = heading_match.group(2)
            nodes.append({"type": f"h{level}", "id": _gen_id(), "children": _parse_rich_text(text)})
            i += 1
            continue

        # 分割线（--- 或 *** 或 ___）— 排除表格分隔行（含 | 的是表格）
        if re.match(r'^[-*_]{3,}$', stripped):
            nodes.append({"type": "divider", "id": _gen_id(), "children": [{"text": ""}]})
            i += 1
            continue

        # 表格行
        if stripped.startswith("|"):
            table_lines = []
            while i < len(lines) and lines[i].strip().startswith("|"):
                table_lines.append(lines[i].strip())
                i += 1
            table_node = _md_table_to_joyspace_table(table_lines)
            if table_node:
                nodes.append(table_node)
            continue

        # 列表项：- 开头 或 * 开头（但 ** 加粗不是列表）
        list_match = re.match(r'^-\s+(.*)', stripped) or re.match(r'^\*(?!\*)\s+(.*)', stripped)
        if list_match:
            nodes.append({
                "type": "list",
                "id": _gen_id(),
                "value": "bullet",
                "indent": 0,
                "children": _parse_rich_text(list_match.group(1)),
            })
            i += 1
            continue

        # 普通段落
        nodes.append({"type": "p", "id": _gen_id(), "children": _parse_rich_text(stripped)})
        i += 1

    return nodes


def generate_joyspace_json(md_path: str, output_path: str = None) -> str:
    """
    读取 MD 文件，转为 JoySpace content JSON 并保存。
    返回 JSON 文件路径。
    """
    with open(md_path, "r", encoding="utf-8-sig") as f:
        md_text = f.read()

    img_dir = os.path.dirname(os.path.abspath(md_path))
    content_json = md_to_joyspace_json(md_text, img_dir)

    if output_path is None:
        base = os.path.splitext(md_path)[0]
        output_path = base + "_joyspace.json"

    with open(output_path, "w", encoding="utf-8") as f:
        json.dump(content_json, f, ensure_ascii=False, indent=2)

    print(f"[JoySpace] content JSON 已生成: {output_path}")
    return output_path


# ── CLI 入口 ───────────────────────────────────────────────
def main():
    parser = argparse.ArgumentParser(description='标准趋势图生成器')
    parser.add_argument('--json', type=str, help='JSON 配置文件路径或内联 JSON 字符串')
    parser.add_argument('--title', type=str, default='同比趋势')
    parser.add_argument('--target', type=str, help='目标值，逗号分隔（null 表示空）')
    parser.add_argument('--yoy26', type=str, help='26年同比率，逗号分隔')
    parser.add_argument('--yoy25', type=str, help='25年同比率，逗号分隔')
    parser.add_argument('--output', '-o', type=str, default='trend_chart.png')
    parser.add_argument('--months', type=str, help='X轴标签，逗号分隔')
    parser.add_argument('--legend-target', type=str, help='目标线图例名称')
    parser.add_argument('--legend-yoy26', type=str, help='26年线图例名称')
    parser.add_argument('--legend-yoy25', type=str, help='25年线图例名称')
    parser.add_argument('--color-target', type=str, help='目标线颜色')
    parser.add_argument('--color-yoy26', type=str, help='26年线颜色')
    parser.add_argument('--color-yoy25', type=str, help='25年线颜色')
    parser.add_argument('--joyspace-json', type=str,
                        help='将指定 MD 文件转为 JoySpace content JSON（图片 base64 嵌入），输出路径可选')

    args = parser.parse_args()

    # ── 从 JSON 加载 ──
    if args.json:
        if os.path.isfile(args.json):
            with open(args.json, 'r', encoding='utf-8') as f:
                cfg = json.load(f)
        else:
            cfg = json.loads(args.json)

        generate_chart(
            title=cfg.get("title", args.title),
            target_values=cfg["target_values"],
            yoy_26_values=cfg["yoy_26_values"],
            yoy_25_values=cfg["yoy_25_values"],
            output_path=cfg.get("output", args.output),
            months=cfg.get("months"),
            legend_names=cfg.get("legend_names"),
            colors=cfg.get("colors"),
        )
        return

    # ── 从命令行参数加载 ──
    def parse_list(s):
        if not s:
            return []
        return [v.strip() if v.strip().lower() != 'null' else None for v in s.split(',')]

    legend_names = {}
    if args.legend_target:
        legend_names["target"] = args.legend_target
    if args.legend_yoy26:
        legend_names["yoy_26"] = args.legend_yoy26
    if args.legend_yoy25:
        legend_names["yoy_25"] = args.legend_yoy25

    colors = {}
    if args.color_target:
        colors["target"] = args.color_target
    if args.color_yoy26:
        colors["yoy_26"] = args.color_yoy26
    if args.color_yoy25:
        colors["yoy_25"] = args.color_yoy25

    generate_chart(
        title=args.title,
        target_values=parse_list(args.target),
        yoy_26_values=parse_list(args.yoy26),
        yoy_25_values=parse_list(args.yoy25),
        output_path=args.output,
        months=parse_list(args.months) if args.months else None,
        legend_names=legend_names or None,
        colors=colors or None,
    )

    # ── JoySpace content JSON 转换 ──
    if args.joyspace_json:
        # --joyspace-json 可以是 "md文件路径" 或 "md文件路径,输出json路径"
        parts = args.joyspace_json.split(",")
        md_path = parts[0].strip()
        json_out = parts[1].strip() if len(parts) > 1 else None
        generate_joyspace_json(md_path, json_out)


if __name__ == '__main__':
    main()
