# -*- coding: utf-8 -*-
"""
doco CLI 入口
P1: doco split 子命令
P3: doco process 子命令(带 --input-a-draft 和 --cleanup-level)
"""

import click
import sys
from pathlib import Path

# P1 相关
from .video_split import split_video


@click.group()
@click.version_option(version="0.1.0")
def main():
    """TPS 中台 - 终版文稿生成工具"""
    pass


@main.command("split")
@click.option(
    "--episode-id",
    required=True,
    help="节目 ID,如 ep001_20260612_fangkong_fandao",
)
@click.option(
    "--input-video",
    required=True,
    type=click.Path(exists=True),
    help="输入视频文件路径",
)
@click.option(
    "--output-dir",
    required=True,
    type=click.Path(),
    help="输出目录(work/ 路径)",
)
@click.option(
    "--hash-algorithm",
    default="dhash",
    type=click.Choice(["dhash", "phash"]),
    help="哈希算法:dhash(默认,对边缘敏感) 或 phash(感知哈希)",
)
@click.option(
    "--phash-threshold",
    default=2,
    type=int,
    help="pHash 海明距离阈值(默认 2)",
)
@click.option(
    "--dhash-threshold",
    default=5,
    type=int,
    help="dHash 海明距离阈值(默认 5)",
)
@click.option(
    "--iou-threshold",
    default=0.95,
    type=float,
    help="IoU 保底阈值:二值化帧间 IoU > 此值视为同字幕(默认 0.95)",
)
@click.option(
    "--dry-run",
    is_flag=True,
    default=False,
    help="只抽帧+裁切,不调 OCR API;用于验证裁切框位置是否正确",
)
def split(
    episode_id: str,
    input_video: str,
    output_dir: str,
    hash_algorithm: str,
    phash_threshold: int,
    dhash_threshold: int,
    iou_threshold: float,
    dry_run: bool,
):
    """
    P1: 视频双路拆分

    A 路:抽帧 + 空白帧过滤 + 哈希变化检测 + OCR → B 稿 txt
    B 路:提取音频(16kHz/单声道/16bit WAV)

    使用 --dry-run 可跳过 OCR 调用,先验证裁切框位置:
    1. 运行 dry-run
    2. 检查 work/frames/ 下的前几张关键帧小图
    3. 确认字幕被完整框住后,去掉 --dry-run 跑正式版
    """
    video_path = Path(input_video)
    out_dir = Path(output_dir)

    click.echo(f"[doco split] episode_id={episode_id}")
    click.echo(f"[doco split] input_video={video_path}")
    click.echo(f"[doco split] output_dir={out_dir}")
    click.echo(f"[doco split] hash_algorithm={hash_algorithm}")
    click.echo(f"[doco split] phash_threshold={phash_threshold}")
    click.echo(f"[doco split] dhash_threshold={dhash_threshold}")
    click.echo(f"[doco split] iou_threshold={iou_threshold}")
    click.echo(f"[doco split] dry_run={dry_run}")

    try:
        result = split_video(
            video_path=video_path,
            output_dir=out_dir,
            episode_id=episode_id,
            hash_algorithm=hash_algorithm,
            phash_threshold=phash_threshold,
            dhash_threshold=dhash_threshold,
            iou_threshold=iou_threshold,
            dry_run=dry_run,
        )
        if dry_run:
            click.echo(f"[ok] 关键帧索引: {result['keyframes_path']}")
            click.echo(f"[ok] 音频: {result['audio_path']}")
            click.echo(f"[ok] 关键帧数量: {result['keyframe_count']}")
            click.echo("[ok] dry-run 完成,请检查 frames/ 目录下的关键帧小图")
        else:
            click.echo(f"[ok] B 稿: {result['b_manuscript_path']}")
            click.echo(f"[ok] 音频: {result['audio_path']}")
            click.echo(f"[ok] 关键帧索引: {result['keyframes_path']}")
            click.echo(f"[ok] 关键帧数量: {result['keyframe_count']}")
    except Exception as e:
        click.echo(f"[error] {e}", err=True)
        sys.exit(1)


@main.command("process")
@click.option("--episode-id", required=True, help="节目 ID")
@click.option("--input-video", required=True, type=click.Path(exists=True), help="输入视频")
@click.option("--input-a-draft", required=True, type=click.Path(exists=True), help="A 稿 docx")
@click.option("--output-dir", required=True, type=click.Path(), help="输出目录")
@click.option(
    "--cleanup-level",
    default="medium",
    type=click.Choice(["keep_all", "medium", "clean"]),
    help="口语清理档位(默认 medium)",
)
def process(
    episode_id: str,
    input_video: str,
    input_a_draft: str,
    output_dir: str,
    cleanup_level: str,
):
    """
    P3: 三方融合全流程
    需要 A 稿 + B 稿(本命令调用 split) + ASR 结果,融合输出终版 docx + 差异报告
    """
    click.echo("[doco process] P3 全流程暂未实现,请先使用 split 命令")
    sys.exit(1)


if __name__ == "__main__":
    main()
