# @CODE:CLI-001 | SPEC: SPEC-CLI-001/spec.md | TEST: tests/unit/test_cli_commands.py
"""MoAI-ADK CLI Entry Point

Implements the CLI entry point:
- Click-based CLI framework
- Rich console terminal output
- ASCII logo rendering
- --version and --help options
- Five core commands: init, doctor, status, backup, update
"""

import sys

import click
import pyfiglet
from rich.console import Console

from moai_adk import __version__
from moai_adk.cli.commands.backup import backup
from moai_adk.cli.commands.doctor import doctor
from moai_adk.cli.commands.init import init
from moai_adk.cli.commands.status import status
from moai_adk.cli.commands.update import update

console = Console()


def show_logo() -> None:
    """Render the MoAI-ADK ASCII logo with Pyfiglet"""
    # Generate the "MoAI-ADK" banner using the ansi_shadow font
    logo = pyfiglet.figlet_format("MoAI-ADK", font="ansi_shadow")

    # Print with Rich styling
    console.print(logo, style="cyan bold", highlight=False)
    console.print("  Modu-AI's Agentic Development Kit w/ SuperAgent 🎩 Alfred", style="yellow bold")
    console.print()
    console.print("  Version: ", style="green", end="")
    console.print(__version__, style="cyan bold")
    console.print()
    console.print("  Tip: Run ", style="yellow", end="")
    console.print("uv run moai-adk --help", style="cyan", end="")
    console.print(" to see available commands", style="yellow")


@click.group(invoke_without_command=True)
@click.version_option(version=__version__, prog_name="MoAI-ADK")
@click.pass_context
def cli(ctx: click.Context) -> None:
    """MoAI Agentic Development Kit

    SPEC-First TDD Framework with Alfred SuperAgent
    """
    # Display the logo when no subcommand is invoked
    if ctx.invoked_subcommand is None:
        show_logo()

cli.add_command(init)
cli.add_command(doctor)
cli.add_command(status)
cli.add_command(backup)
cli.add_command(update)


# 링크 검증 명령
@click.command(name='validate-links')
@click.option('--file', '-f', default='README.ko.md', help='검증할 파일 경로 (기본값: README.ko.md)')
@click.option('--max-concurrent', '-c', type=int, default=3, help='동시에 검증할 최대 링크 수 (기본값: 3)')
@click.option('--timeout', '-t', type=int, default=8, help='요청 타임아웃 (초) (기본값: 8)')
@click.option('--output', '-o', help='결과를 저장할 파일 경로')
@click.option('--verbose', '-v', is_flag=True, help='상세한 진행 상황 표시')
def validate_links(file, max_concurrent, timeout, output, verbose):
    """온라인 문서 링크 검증"""
    from moai_adk.cli.commands.validate_links import run_command as validate_links_run

    # CLI 명령 실행
    sys.exit(validate_links_run(locals()))


# 사용자 경험 개선 명령
@click.command(name='improve-ux')
@click.option('--url', '-u', default='https://adk.mo.ai.kr', help='분석할 URL (기본값: https://adk.mo.ai.kr)')
@click.option('--output', '-o', help='분석 결과를 저장할 파일 경로')
@click.option('--format', '-f', type=click.Choice(['json', 'markdown', 'text']),
              default='markdown', help='출력 형식 (기본값: markdown)')
@click.option('--verbose', '-v', is_flag=True, help='상세한 진행 상황 표시')
@click.option('--max-workers', '-w', type=int, default=5, help='동시에 처리할 최대 작업 수 (기본값: 5)')
def improve_ux(url, output, format, verbose, max_workers):
    """사용자 경험 개선 분석"""
    # 임시 args 객체 생성
    class Args:
        def __init__(self, **kwargs):
            for key, value in kwargs.items():
                setattr(self, key, value)

    args = Args(url=url, output=output, format=format, verbose=verbose, max_workers=max_workers)

    # CLI 명령 실행
    from moai_adk.cli.commands.improve_user_experience import run_command as improve_ux_run
    sys.exit(improve_ux_run(args))


cli.add_command(validate_links)
cli.add_command(improve_ux)


def main() -> int:
    """CLI entry point"""
    try:
        cli(standalone_mode=False)
        return 0
    except click.Abort:
        # User cancelled with Ctrl+C
        return 130
    except click.ClickException as e:
        e.show()
        return e.exit_code
    except Exception as e:
        console.print(f"[red]Error:[/red] {e}")
        return 1
    finally:
        # Flush the output buffer explicitly
        console.file.flush()


if __name__ == "__main__":
    sys.exit(main())


# Sync 명령어 추가
@click.command(name='sync')
@click.option('--skip-docs', is_flag=True, help='문서 동기화 건너뛰기')
@click.option('--skip-tags', is_flag=True, help='TAG 검증 건너뛰기')
@click.option('--apply-dedup', is_flag=True, help='TAG 중복 제거 적용')
@click.option('--dry-run', is_flag=True, default=True, help='시뮬레이션 모드 (기본값: True)')
def sync_command_func(skip_docs, skip_tags, apply_dedup, dry_run):
    """MoAI-ADK 프로젝트 동기화 (TAG 중복 제거 포함)"""
    options = {
        "skip_docs": skip_docs,
        "skip_tags": skip_tags,
        "apply_dedup": apply_dedup,
        "dry_run": dry_run
    }

    from moai_adk.cli.commands.sync import sync as sync_cli
    sys.exit(sync_cli(options))

cli.add_command(sync_command_func)
