# Copyright (C) 2026 GoodData Corporation

"""CLI handlers for commit and alias commands."""

from __future__ import annotations

import argparse
import shutil
import sys
from pathlib import Path

from aida_mcp.server import mcp_install
from aida_mcp.server.commit_cli import CommitMessageInput, commit_with_message, render_commit_message
from aida_mcp.tools.core.git_policy_config import load_git_policy


def commit_cmd(args: argparse.Namespace) -> None:
    workspace_root = Path(args.workspace_root).expanduser().resolve() if args.workspace_root else Path.cwd().resolve()
    git_policy = load_git_policy(workspace_root)
    body_value = ""
    if args.body is not None:
        body_value = str(args.body)
    elif args.body_file:
        body_value = Path(args.body_file).read_text(encoding="utf-8")
    elif bool(args.body_stdin):
        body_value = sys.stdin.read()
    elif args.body_line:
        body_value = "\n".join([str(line) for line in args.body_line])

    ai_share_values: list[str]
    if args.ai_share_auto:
        if not git_policy.commit.enable_ai_share_auto:
            raise ValueError(
                "ai-share-auto is disabled by git policy. "
                "Set git_policy.commit.enable_ai_share_auto: true in .aida/git_policy.yaml to enable it."
            )
        ai_share_values = [f"{str(args.ai_share_auto).strip().lower()}=100"]
    else:
        ai_share_values = [str(x) for x in (args.ai_share or [])]

    message = render_commit_message(
        CommitMessageInput(
            commit_type=str(args.type),
            scope=str(args.scope) if args.scope else None,
            title=str(args.title),
            body=body_value or None,
            risk=str(args.risk),
            jira=[str(x) for x in (args.jira or [])],
            co_authored_by=[str(x) for x in (args.co_authored_by or [])],
            ai_share=ai_share_values,
        ),
        policy=git_policy.commit,
    )

    if bool(args.dry_run):
        print("[aida-mcp][commit] dry-run: would commit with message:")
        print("---")
        print(message.rstrip())
        print("---")
        return

    repo_root, staged_files = commit_with_message(
        workspace_root=workspace_root,
        message=message,
        stage_all=bool(args.all),
    )
    print(f"[aida-mcp][commit] committed in {repo_root}")
    print("[aida-mcp][commit] files:")
    for file_path in staged_files:
        print(f"  - {file_path}")


def alias_status_cmd(args: argparse.Namespace) -> None:
    name = str(args.name or "aida")
    resolved_on_path = shutil.which(name)

    command_path = mcp_install.resolve_self_command_path(sys.argv[0])
    scripts_dir = command_path.parent
    alias_path = scripts_dir / name

    print(f"[aida-mcp][alias] name: {name}")
    print(f"[aida-mcp][alias] aida-mcp: {command_path}")
    print(f"[aida-mcp][alias] scripts_dir: {scripts_dir}")
    print(f"[aida-mcp][alias] alias_path: {alias_path}")

    if resolved_on_path:
        print(f"[aida-mcp][alias] {name} resolves on PATH: {resolved_on_path}")
    else:
        print(f"[aida-mcp][alias] {name} not found on PATH")

    if alias_path.exists():
        print("[aida-mcp][alias] alias file exists next to aida-mcp")
    else:
        print("[aida-mcp][alias] alias file NOT present next to aida-mcp")


def alias_install_cmd(args: argparse.Namespace) -> None:
    name = str(args.name or "aida")
    force = bool(getattr(args, "force", False))

    resolved_on_path = shutil.which(name)
    if resolved_on_path and not force:
        print(f"[aida-mcp][alias][error] Refusing to install alias '{name}': command already exists on PATH.")
        print(f"[aida-mcp][alias][error] Found: {resolved_on_path}")
        print("[aida-mcp][alias][error] Keep using 'aida-mcp', or rerun with --force if you understand the risk.")
        raise SystemExit(2)

    command_path = mcp_install.resolve_self_command_path(sys.argv[0])
    scripts_dir = command_path.parent
    alias_path = scripts_dir / name

    wrapper = (
        "#!/usr/bin/env sh\n"
        "# Generated by `aida-mcp alias install`.\n"
        "# This wrapper lives next to the installed `aida-mcp` script.\n"
        "set -e\n"
        'exec "$(dirname "$0")/aida-mcp" "$@"\n'
    )

    alias_path.write_text(wrapper, encoding="utf-8")
    alias_path.chmod(0o755)
    print(f"[aida-mcp][alias] Installed alias '{name}' at {alias_path}")
    if resolved_on_path:
        print(
            f"[aida-mcp][alias] Note: '{name}' already existed on PATH ({resolved_on_path}); PATH precedence decides which runs."
        )


def alias_uninstall_cmd(args: argparse.Namespace) -> None:
    name = str(args.name or "aida")

    command_path = mcp_install.resolve_self_command_path(sys.argv[0])
    scripts_dir = command_path.parent
    alias_path = scripts_dir / name

    if not alias_path.exists():
        print(f"[aida-mcp][alias] Alias '{name}' is not installed at {alias_path}")
        return

    try:
        current = alias_path.read_text(encoding="utf-8")
    except Exception:
        current = ""

    marker = "# Generated by `aida-mcp alias install`."
    if marker not in current:
        print(
            f"[aida-mcp][alias][error] Refusing to remove '{alias_path}': file does not look like an aida-mcp alias wrapper."
        )
        print("[aida-mcp][alias][error] Remove it manually if you are sure.")
        raise SystemExit(2)

    alias_path.unlink()
    print(f"[aida-mcp][alias] Removed alias '{name}' at {alias_path}")
