"""Start command - launch TUI file manager."""

import typer
from rich.console import Console

from kitech_repository.cli.utils import get_cli_command_name
from kitech_repository.core.auth import AuthManager
from kitech_repository.core.client import KitechClient
from kitech_repository.core.config import Config
from kitech_repository.core.exceptions import AuthenticationError
from kitech_repository.tui import KitechTUI

console = Console(highlight=False)
app = typer.Typer()


@app.callback(invoke_without_command=True)
def start(
    ctx: typer.Context,
    repository_id: int = typer.Argument(
        None, help="리포지토리 ID (선택사항 - 입력하지 않으면 선택 화면 표시)"
    ),
):
    """TUI 파일 관리자 시작"""
    try:
        # Check authentication first
        auth_manager = AuthManager()
        if not auth_manager.is_authenticated():
            console.print("[red]❌ 인증되지 않았습니다.[/red]")
            console.print(f"먼저 로그인해주세요: [cyan]{get_cli_command_name()} login[/cyan]")
            raise typer.Exit(1)

        # Initialize client (will automatically use AuthManager internally)
        config = Config.load()
        client = KitechClient(config=config)

        # Launch Textual TUI
        tui_app = KitechTUI(client=client, initial_repo_id=repository_id)
        tui_app.run()

    except AuthenticationError:
        console.print("[red]❌ 인증 오류[/red]")
        console.print(f"먼저 로그인해주세요: [cyan]{get_cli_command_name()} login[/cyan]")
        raise typer.Exit(1)
    except typer.Exit:
        raise
    except KeyboardInterrupt:
        console.print("\n👋 파일 관리자를 종료했습니다.")
    except Exception as e:
        import traceback

        console.print(f"[red]❌ 오류: {e}[/red]")
        console.print(f"[red]유형: {type(e).__name__}[/red]")
        console.print(f"[red]상세: {traceback.format_exc()}[/red]")
        raise typer.Exit(1)
