# -*- coding: utf-8 -*-
"""/git 命令族：Git 归因信息展示（Phase 7 Tier 1 BF）。

子命令：
- /git blame <file> [start-end] — 行级作者归因
- /git log [N]                  — 最近 N 条提交（默认 10）
- /git stats                    — 按作者统计提交数
- /git show <sha>               — 显示指定 commit 摘要

借鉴 zhikuncode CommitAttributionService.java + abyss commands/diff.py 表格风格。
"""
from __future__ import annotations

import os
from typing import Optional

from abyss.vcs.commit_attribution import CommitAttributionService

__all__ = ["handle_git"]


def _get_service() -> CommitAttributionService:
    """获取默认服务实例并同步 working_dir 为当前 cwd。"""
    svc = CommitAttributionService.get_default_service() if hasattr(CommitAttributionService, "get_default_service") else None
    # 直接用模块级单例
    from abyss.vcs.commit_attribution import get_default_service
    svc = get_default_service()
    svc.set_working_dir(os.getcwd())
    return svc


def handle_git(args: str) -> str:
    """/git 命令入口。

    Args:
        args: /git 后的参数字符串（如 "blame file.py 1-10"）

    Returns:
        格式化的输出字符串
    """
    parts = args.strip().split(None, 1)
    if not parts or not parts[0]:
        return _usage()

    sub = parts[0].lower()
    rest = parts[1] if len(parts) > 1 else ""

    if sub == "blame":
        return _handle_blame(rest)
    if sub == "log":
        return _handle_log(rest)
    if sub == "stats":
        return _handle_stats()
    if sub == "show":
        return _handle_show(rest)
    return _usage()


def _usage() -> str:
    return (
        "用法: /git <子命令> [参数]\n\n"
        "子命令：\n"
        "  /git blame <file> [start-end]  行级作者归因\n"
        "  /git log [N]                   最近 N 条提交（默认 10）\n"
        "  /git stats                     按作者统计提交数\n"
        "  /git show <sha>                显示指定 commit 摘要"
    )


def _handle_blame(args: str) -> str:
    """处理 /git blame <file> [start-end]。"""
    parts = args.split()
    if not parts:
        return "用法: /git blame <file> [start-end]"
    file_path = parts[0]
    line_range: Optional[tuple] = None
    if len(parts) > 1:
        # 解析 "1-10" 或 "5"
        range_str = parts[1]
        try:
            if "-" in range_str:
                s, e = range_str.split("-", 1)
                line_range = (int(s), int(e))
            else:
                line_range = (int(range_str), int(range_str))
        except ValueError:
            return f"[ERR] 行范围格式错误: {range_str}（应为 N 或 N-M）"

    svc = _get_service()
    if not svc.is_git_repo():
        return "[ERR] 当前目录不是 git 仓库"

    if line_range:
        result = svc.blame(file_path, start=line_range[0], end=line_range[1])
    else:
        result = svc.blame(file_path)

    if not result:
        return f"[INFO] 无法获取 {file_path} 的归因信息（文件不存在或无提交）"

    lines = [f"📝 {file_path} 行级归因（共 {len(result)} 行）"]
    lines.append("")
    lines.append(f"{'行号':<6}{'作者':<20}{'提交':<10}内容")
    lines.append("-" * 80)
    for bl in result:
        # 截断内容防止超长
        content = bl.content[:40] + ("..." if len(bl.content) > 40 else "")
        short_sha = bl.commit_hash[:8] if bl.commit_hash else "?"
        author = bl.author[:18]
        lines.append(f"{bl.line_number:<6}{author:<20}{short_sha:<10}{content}")
    return "\n".join(lines)


def _handle_log(args: str) -> str:
    """处理 /git log [N]。"""
    limit = 10
    if args.strip():
        try:
            limit = int(args.strip())
            if limit <= 0 or limit > 100:
                return "[ERR] N 应在 1-100 范围"
        except ValueError:
            return f"[ERR] N 应为整数: {args}"

    svc = _get_service()
    if not svc.is_git_repo():
        return "[ERR] 当前目录不是 git 仓库"

    commits = svc.log(limit=limit)
    if not commits:
        return "[INFO] 仓库无提交记录"

    lines = [f"📋 最近 {len(commits)} 条提交（倒序）"]
    lines.append("")
    for c in commits:
        short_sha = c.hash[:8]
        lines.append(f"  {short_sha}  {c.author:<15}  {c.date}")
        lines.append(f"    {c.message}")
    return "\n".join(lines)


def _handle_stats() -> str:
    """处理 /git stats。"""
    svc = _get_service()
    if not svc.is_git_repo():
        return "[ERR] 当前目录不是 git 仓库"

    stats = svc.author_stats()
    if not stats:
        return "[INFO] 无作者贡献统计"

    lines = ["👥 作者贡献统计"]
    lines.append("")
    lines.append(f"{'作者':<25}{'邮箱':<35}{'提交数':>8}")
    lines.append("-" * 70)
    for s in stats:
        lines.append(f"{s.author[:24]:<25}{s.email[:34]:<35}{s.commit_count:>8}")
    return "\n".join(lines)


def _handle_show(args: str) -> str:
    """处理 /git show <sha>。"""
    sha = args.strip()
    if not sha:
        return "用法: /git show <sha>"

    svc = _get_service()
    if not svc.is_git_repo():
        return "[ERR] 当前目录不是 git 仓库"

    info = svc.commit_summary(sha)
    if info is None:
        return f"[ERR] 未找到 commit: {sha}"

    lines = [
        f"🔍 提交摘要",
        "",
        f"  Hash:    {info.hash}",
        f"  作者:   {info.author} <{info.email}>",
        f"  时间:   {info.date}",
        f"  消息:   {info.message}",
    ]
    return "\n".join(lines)
