#!/usr/bin/env python3
"""
append_event.py - 将一条新事项追加到 Markdown 日程文件

用法：
  python3 append_event.py \
    --file /home/node/.openclaw/workspace/日程.md \
    --date 2026-03-03 \
    --start 15:00 \
    --end 16:00 \
    --title "客户会议" \
    [--location "线上"] \
    [--participants "张三"] \
    [--priority 中] \
    [--advance 15] \
    [--note "带方案"] \
    [--type task]   # task = 写入待提醒任务表，默认写入主日程表
"""
from __future__ import annotations

import sys
import os
import re
import argparse
from datetime import datetime, date
from typing import Optional


def parse_args():
    p = argparse.ArgumentParser(description="追加日程事项到 Markdown 文件")
    p.add_argument("--file", required=True, help="日程 Markdown 文件路径")
    p.add_argument("--date", required=True, help="日期 YYYY-MM-DD")
    p.add_argument("--start", default="", help="开始时间 HH:MM")
    p.add_argument("--end", default="", help="结束时间 HH:MM")
    p.add_argument("--title", required=True, help="事项名称")
    p.add_argument("--location", default="", help="地点")
    p.add_argument("--participants", default="", help="参与者")
    p.add_argument("--priority", default="中", choices=["高", "中", "低"], help="优先级")
    p.add_argument("--advance", default="15", help="提前提醒分钟数")
    p.add_argument("--note", default="", help="备注")
    p.add_argument("--type", default="schedule", choices=["schedule", "task"],
                   help="写入主日程表(schedule)还是待提醒任务表(task)")
    return p.parse_args()


def expand_path(path: str) -> str:
    return os.path.expanduser(path)


def read_file(path: str) -> str:
    if not os.path.exists(path):
        return ""
    with open(path, encoding="utf-8") as f:
        return f.read()


def write_file(path: str, content: str):
    os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        f.write(content)


def make_schedule_row(args) -> str:
    """生成主日程表的一行"""
    advance = args.advance if args.advance else "15"
    return (
        f"| {args.date} | {args.start} | {args.end} | {args.title} "
        f"| {args.location} | {args.participants} | {args.priority} "
        f"| {advance} | {args.note} |"
    )


def make_task_row(args) -> str:
    """生成待提醒任务表的一行"""
    # 任务表：截止日期 | 事项 | 负责人 | 优先级 | 提前提醒 | 备注
    advance_days = ""
    try:
        adv_min = int(args.advance)
        if adv_min >= 1440:
            days = adv_min // 1440
            advance_days = f"提前{days}天"
        else:
            advance_days = str(adv_min)
    except ValueError:
        advance_days = args.advance

    return (
        f"| {args.date} | {args.title} | {args.participants} "
        f"| {args.priority} | {advance_days} | {args.note} |"
    )


SCHEDULE_HEADER = "| 日期       | 开始时间 | 结束时间 | 事项"
SCHEDULE_HEADER_ALT = "| 日期 | 开始时间"
TASK_HEADER = "| 截止日期"

SCHEDULE_TABLE_BLOCK = """\
## 日程

| 日期       | 开始时间 | 结束时间 | 事项         | 地点 | 参与者 | 优先级 | 提前(分钟) | 备注 |
|------------|----------|----------|--------------|------|--------|--------|------------|------|
"""

TASK_TABLE_BLOCK = """\
## 待提醒任务

| 截止日期   | 事项 | 负责人 | 优先级 | 提前提醒 | 备注 |
|------------|------|--------|--------|----------|------|
"""

DEFAULT_FILE_TEMPLATE = """\
<!-- skill: schedule-reminder -->
# 我的日程

> 提醒渠道：last
> 默认提前提醒：15

{schedule_block}
{task_block}"""


def find_table_end(lines: list, start_idx: int) -> int:
    """从 start_idx 往下找到表格结束位置（返回最后一行表格的 index + 1）"""
    i = start_idx
    last_table_line = start_idx
    while i < len(lines):
        stripped = lines[i].strip()
        if stripped.startswith("|"):
            last_table_line = i
        elif stripped == "" and i > start_idx:
            # 空行可能是表格后的分隔，继续看下一行
            if i + 1 < len(lines) and not lines[i + 1].strip().startswith("|"):
                break
        elif not stripped.startswith("|") and stripped != "":
            break
        i += 1
    return last_table_line + 1


def insert_row_into_table(content: str, new_row: str, header_pattern: str) -> Optional[str]:
    """在找到的表格末尾插入新行，返回修改后的内容；找不到返回 None"""
    lines = content.splitlines(keepends=True)
    header_idx = None
    for i, line in enumerate(lines):
        if line.strip().startswith(header_pattern.strip()):
            header_idx = i
            break

    if header_idx is None:
        return None

    end_idx = find_table_end(lines, header_idx)
    lines.insert(end_idx, new_row + "\n")
    return "".join(lines)


def append_to_file(file_path: str, args) -> str:
    """主逻辑：读取文件 → 找表格 → 插入新行 → 写回"""
    content = read_file(file_path)

    if args.type == "task":
        new_row = make_task_row(args)
        updated = insert_row_into_table(content, new_row, "| 截止日期")
        if updated is None:
            # 没有任务表，追加一个
            if content and not content.endswith("\n"):
                content += "\n"
            content += "\n" + TASK_TABLE_BLOCK + new_row + "\n"
            updated = content
    else:
        new_row = make_schedule_row(args)
        updated = insert_row_into_table(content, new_row, "| 日期")
        if updated is None:
            # 没有日程表，追加一个
            if not content:
                # 文件为空，创建完整模板
                updated = DEFAULT_FILE_TEMPLATE.format(
                    schedule_block=SCHEDULE_TABLE_BLOCK + new_row,
                    task_block=TASK_TABLE_BLOCK,
                )
            else:
                if not content.endswith("\n"):
                    content += "\n"
                content += "\n" + SCHEDULE_TABLE_BLOCK + new_row + "\n"
                updated = content

    return updated


def main():
    args = parse_args()
    file_path = expand_path(args.file)

    updated_content = append_to_file(file_path, args)
    write_file(file_path, updated_content)

    # 输出确认信息
    event_type = "任务" if args.type == "task" else "日程"
    time_str = f"{args.start}" + (f" – {args.end}" if args.end else "")
    print(f"✅ 已写入{event_type}：{args.date} {time_str} {args.title} → {file_path}")


if __name__ == "__main__":
    main()
