"""CLI entry point — argument parsing and startup."""

import argparse
import shutil
import sys

from . import __version__
from . import config


def main():
    parser = argparse.ArgumentParser(
        prog="claude-link",
        description="Connect Claude Code to Telegram in one command",
    )
    parser.add_argument(
        "-v", "--version", action="version", version=f"claude-link {__version__}"
    )
    parser.add_argument(
        "--setup", action="store_true", help="Re-run the setup wizard"
    )
    parser.add_argument(
        "--enable-voice", action="store_true", help="Enable voice transcription (requires OpenAI key)"
    )
    parser.add_argument(
        "--workspace", type=str, help="Override workspace directory"
    )
    args = parser.parse_args()

    # Handle --enable-voice
    if args.enable_voice:
        cfg = config.load()
        if cfg is None:
            print("❌ Run claude-link first to complete initial setup.")
            sys.exit(1)
        api_key = config.voice_wizard()
        if api_key:
            cfg["openai_api_key"] = api_key
            config.save(cfg)
        sys.exit(0)

    # Load or create config
    cfg = config.load()
    if cfg is None or args.setup:
        cfg = config.setup_wizard()

    # Override workspace if provided
    if args.workspace:
        cfg["workspace"] = args.workspace

    # Check claude is available
    claude_path = cfg.get("claude_path", "claude")
    if not shutil.which(claude_path):
        print(f"❌ Claude Code not found at '{claude_path}'")
        print("   Install it: https://docs.anthropic.com/en/docs/claude-code")
        print(f"   Or set a custom path with: claude-link --setup")
        sys.exit(1)

    # Start the bot
    voice = "on" if cfg.get("openai_api_key") else "off"
    print(f"\n🌉 claude-link v{__version__}")
    print(f"   Workspace: {cfg['workspace']}")
    print(f"   Claude: {claude_path}")
    print(f"   Chat ID: {cfg['chat_id']}")
    print(f"   Voice: {voice}")
    print()

    from .bot import run_bot

    run_bot(cfg)
