"""Configuration management — load/save ~/.claude-bridge.json"""

import json
import os
import secrets
from pathlib import Path

import httpx

CONFIG_PATH = Path.home() / ".claude-link.json"

DEFAULTS = {
    "claude_path": "claude",
    "workspace": str(Path.home()),
}

BOT_DESCRIPTION = "Claude Code on Telegram — powered by claude-link"
BOT_SHORT_DESCRIPTION = "Send me a message and I'll forward it to Claude Code"
BOT_COMMANDS = [
    {"command": "cancel", "description": "Stop current task and clear queue"},
    {"command": "new", "description": "Start a fresh conversation"},
    {"command": "status", "description": "Show bot info"},
    {"command": "help", "description": "Show available commands"},
]


def load() -> dict | None:
    """Load config from disk. Returns None if not found."""
    if not CONFIG_PATH.exists():
        return None
    return json.loads(CONFIG_PATH.read_text())


def save(config: dict):
    """Save config to disk with restricted permissions (owner-only)."""
    CONFIG_PATH.write_text(json.dumps(config, indent=2) + "\n")
    try:
        os.chmod(CONFIG_PATH, 0o600)
    except OSError:
        pass  # Windows doesn't support Unix permissions


def _bot_api(token: str, method: str, payload: dict = None) -> dict | None:
    """Call a Telegram Bot API method."""
    try:
        url = f"https://api.telegram.org/bot{token}/{method}"
        if payload:
            resp = httpx.post(url, json=payload, timeout=10)
        else:
            resp = httpx.get(url, timeout=10)
        data = resp.json()
        if data.get("ok"):
            return data.get("result")
    except Exception:
        pass
    return None


def _configure_bot(token: str):
    """Auto-configure bot description and commands."""
    _bot_api(token, "setMyDescription", {"description": BOT_DESCRIPTION})
    _bot_api(token, "setMyShortDescription", {"short_description": BOT_SHORT_DESCRIPTION})
    _bot_api(token, "setMyCommands", {"commands": BOT_COMMANDS})
    print("  ✅ Bot configured (description + commands)")


def _verify_telegram(token: str, chat_id: int) -> bool:
    """Send a verification code via Telegram and ask user to confirm."""
    code = str(secrets.randbelow(9000) + 1000)

    print("  🔐 Sending verification code to your Telegram...")

    resp = _bot_api(token, "sendMessage", {
        "chat_id": chat_id,
        "text": f"🌉 claude-link verification code:\n\n🔑 {code}\n\nEnter this code in your terminal to complete setup.",
    })

    if resp is None:
        print("\n  ❌ Could not send message.")
        print("  → Make sure you've opened the bot link above and pressed Start!")
        return False

    print()
    print("  📱 Check your Telegram — a code was sent!")
    user_code = input("  Enter the 4-digit code: ").strip()

    if user_code == code:
        print("  ✅ Verified!\n")
        return True

    # One retry
    print("  ❌ Wrong code. Try once more:")
    user_code = input("  Enter the 4-digit code: ").strip()

    if user_code == code:
        print("  ✅ Verified!\n")
        return True

    print("  ❌ Verification failed. Check your token and chat ID.\n")
    return False


def voice_wizard() -> str | None:
    """Mini-wizard to enable voice transcription."""
    print()
    print("🎤 Enable voice transcription")
    print("=" * 40)
    print("  Requires an OpenAI API key (for Whisper)")
    print("  → Get one at https://platform.openai.com/api-keys")
    print()

    api_key = input("  OpenAI API Key: ").strip()
    if not api_key:
        print("  ❌ Cancelled.\n")
        return None

    # Validate key with a simple API call
    print("  Validating key...")
    try:
        resp = httpx.get(
            "https://api.openai.com/v1/models",
            headers={"Authorization": f"Bearer {api_key}"},
            timeout=10,
        )
        if resp.status_code != 200:
            print("  ❌ Invalid API key.\n")
            return None
    except Exception:
        print("  ❌ Could not reach OpenAI API.\n")
        return None

    print("  ✅ Voice transcription enabled!\n")
    return api_key


def setup_wizard() -> dict:
    """Interactive first-time setup."""
    print()
    print("🌉 claude-link — Setup")
    print("=" * 40)
    print("  You only need to do this once.")
    print()

    # Step 1: Bot Token
    print("Step 1: Create a Telegram bot")
    print("  → Open https://t.me/BotFather")
    print("  → Send /newbot and follow the steps")
    print("  → Copy the token it gives you")
    print()
    token = input("  Bot Token: ").strip()
    if not token:
        print("\n❌ Token is required.")
        raise SystemExit(1)

    # Validate token and get bot info
    print("\n  Validating token...")
    bot_info = _bot_api(token, "getMe")
    if not bot_info:
        print("  ❌ Invalid token. Please check and try again.")
        raise SystemExit(1)

    bot_username = bot_info.get("username", "")
    bot_name = bot_info.get("first_name", "your bot")
    print(f"  ✅ Connected to @{bot_username} ({bot_name})")
    print()

    # Auto-configure bot
    _configure_bot(token)
    print()

    # Step 2: Chat ID
    print("Step 2: Get your Chat ID")
    print("  → Open https://t.me/userinfobot")
    print("  → It will reply with your ID (a number)")
    print()
    chat_id = input("  Chat ID: ").strip()
    if not chat_id or not chat_id.lstrip("-").isdigit():
        print("\n  ❌ Valid Chat ID is required (must be a number).")
        raise SystemExit(1)
    print()

    # Step 3: Verify connection
    print("Step 3: Verify connection")
    print(f"  → Open your bot: https://t.me/{bot_username}")
    print("  → Press Start if you haven't already")
    print()
    input("  Press Enter when ready...")
    print()

    if not _verify_telegram(token, int(chat_id)):
        raise SystemExit(1)

    # Step 4: Claude path
    print("Step 4: Claude Code CLI path")
    print(f"  → Press Enter to use default: {DEFAULTS['claude_path']}")
    print("  → Only change if claude is installed somewhere else")
    claude_path = input(f"  Claude path [{DEFAULTS['claude_path']}]: ").strip()
    print()

    # Step 5: Workspace
    print("Step 5: Workspace directory")
    print("  → This is where Claude will work (read/edit files)")
    print(f"  → Press Enter to use default: {DEFAULTS['workspace']}")
    workspace = input(f"  Workspace [{DEFAULTS['workspace']}]: ").strip()
    print()

    config = {
        "telegram_token": token,
        "chat_id": int(chat_id),
        "claude_path": claude_path or DEFAULTS["claude_path"],
        "workspace": workspace or DEFAULTS["workspace"],
    }

    save(config)
    print(f"✅ Config saved to {CONFIG_PATH}")
    print()

    # Tip about bot photo
    print("💡 Tip: To set a profile photo for your bot,")
    print("   send /setuserpic to @BotFather")
    print()

    return config
