"""
kwtsms._cli — terminal command entry point.

Registered as the `kwtsms` command by pyproject.toml [project.scripts].

Usage:
    kwtsms setup
    kwtsms verify
    kwtsms balance
    kwtsms send 96598765432 "Your OTP for MYAPP is: 123456"
    kwtsms validate 96598765432 +96512345678 0096511111111
"""

import getpass
import os
import sys

from kwtsms._core import KwtSMS, _load_env_file, _request

_TEST_MODE_WARNING = (
    "\n  TEST MODE — message will be queued but NOT delivered to the handset.\n"
    "  No SMS credits will be consumed.\n"
    "  To send real messages run 'kwtsms setup' and choose Live mode.\n"
)


def _run_setup(env_file: str = ".env") -> None:
    """Interactive first-time setup wizard."""
    print("\n── kwtSMS Setup ──────────────────────────────────────────────────")
    print("Verifies your API credentials and creates a .env file.")
    print("Press Enter to keep the value shown in brackets.\n")

    existing = _load_env_file(env_file)

    # Username
    default_user = existing.get("KWTSMS_USERNAME", "")
    prompt_user = f"API Username [{default_user}]: " if default_user else "API Username: "
    username = input(prompt_user).strip() or default_user

    # Password (hidden)
    default_pass = existing.get("KWTSMS_PASSWORD", "")
    if default_pass:
        raw_pass = getpass.getpass("API Password [keep existing]: ").strip()
        password = raw_pass if raw_pass else default_pass
    else:
        password = getpass.getpass("API Password: ").strip()

    if not username or not password:
        print("\nError: username and password are required.")
        sys.exit(1)

    # Verify credentials
    print("\nVerifying credentials...", end=" ", flush=True)
    try:
        data = _request("balance", {"username": username, "password": password})
        if data.get("result") != "OK":
            err = data.get("description", data.get("code", "Unknown error"))
            print(f"FAILED\nError: {err}")
            sys.exit(1)
        print(f"OK  (Balance: {data.get('available', '?')})")
    except RuntimeError as e:
        print(f"FAILED\nError: {e}")
        sys.exit(1)

    # Fetch Sender IDs
    print("Fetching Sender IDs...", end=" ", flush=True)
    senderids = []
    try:
        sid_data = _request("senderid", {"username": username, "password": password})
        if sid_data.get("result") == "OK":
            senderids = sid_data.get("senderid", [])
    except RuntimeError:
        pass

    if senderids:
        print("OK")
        print("\nAvailable Sender IDs:")
        for i, sid in enumerate(senderids, 1):
            print(f"  {i}. {sid}")
        default_sid = existing.get("KWTSMS_SENDER_ID", senderids[0])
        choice = input(f"\nSelect Sender ID (number or name) [{default_sid}]: ").strip()
        if choice.isdigit() and 1 <= int(choice) <= len(senderids):
            sender_id = senderids[int(choice) - 1]
        else:
            sender_id = choice or default_sid
    else:
        print("(none returned)")
        default_sid = existing.get("KWTSMS_SENDER_ID", "KWT-SMS")
        sender_id = input(f"Sender ID [{default_sid}]: ").strip() or default_sid

    # Send mode
    current_mode = existing.get("KWTSMS_TEST_MODE", "1")
    print("\nSend mode:")
    print("  1. Test mode  — messages queued but NOT delivered, no credits consumed  [default]")
    print("  2. Live mode  — messages delivered to handsets, credits consumed")
    mode_default = "1" if current_mode != "0" else "2"
    mode_choice = input(f"\nChoose [{mode_default}]: ").strip() or mode_default
    test_mode = "0" if mode_choice == "2" else "1"

    if test_mode == "1":
        print("  → Test mode selected.")
    else:
        print("  → Live mode selected. Real messages will be sent and credits consumed.")

    # Log file
    default_log = existing.get("KWTSMS_LOG_FILE", "kwtsms.log")
    log_file_path = input(f"\nLog file path [{default_log}]: ").strip() or default_log

    # Write .env
    content = (
        "# kwtSMS credentials — generated by kwtsms setup\n"
        f"KWTSMS_USERNAME={username}\n"
        f"KWTSMS_PASSWORD={password}\n"
        f"KWTSMS_SENDER_ID={sender_id}\n"
        f"KWTSMS_TEST_MODE={test_mode}\n"
        f"KWTSMS_LOG_FILE={log_file_path}\n"
    )

    try:
        with open(env_file, "w", encoding="utf-8") as f:
            f.write(content)
    except OSError as e:
        print(f"\nError writing {env_file}: {e}")
        sys.exit(1)

    print(f"\n  Saved to {env_file}")
    if test_mode == "1":
        print("  Mode: TEST — messages queued but not delivered (no credits consumed)")
    else:
        print("  Mode: LIVE — messages will be delivered and credits consumed")
    print("  Run 'kwtsms setup' at any time to change settings.")
    print("─────────────────────────────────────────────────────────────────\n")


def main() -> None:
    """Entry point for the `kwtsms` CLI command."""
    args = sys.argv[1:]
    if not args or args[0] in ("-h", "--help"):
        print(__doc__)
        print("Commands: setup | verify | balance | send <mobile> <message> | validate <numbers...>")
        sys.exit(0)

    cmd = args[0].lower()

    if cmd == "setup":
        _run_setup()
        sys.exit(0)

    # Load credentials — auto-prompt setup on first run
    try:
        sms = KwtSMS.from_env()
    except ValueError:
        if not os.path.exists(".env"):
            print("No .env file found. Starting first-time setup...\n")
            _run_setup()
            try:
                sms = KwtSMS.from_env()
            except ValueError as e:
                print(f"Error: {e}")
                sys.exit(1)
        else:
            print("Error: credentials missing or incomplete in .env")
            print("Run 'kwtsms setup' to fix.")
            sys.exit(1)

    if cmd == "verify":
        ok, bal, err = sms.verify()
        if ok:
            print(f"  Credentials valid  |  Balance: {bal}")
            if sms.test_mode:
                print("  Mode: TEST (messages will not be delivered)")
        else:
            print(f"  Credential check failed: {err}")
            sys.exit(1)

    elif cmd == "balance":
        bal = sms.balance()
        if bal is not None:
            print(f"Balance: {bal}")
        else:
            print("Could not retrieve balance")
            sys.exit(1)

    elif cmd == "send":
        if len(args) < 3:
            print("Usage: kwtsms send <mobile> <message>")
            sys.exit(1)
        mobile, message = args[1], " ".join(args[2:])
        if sms.test_mode:
            print(_TEST_MODE_WARNING)
        result = sms.send(mobile, message)
        if result.get("result") == "OK":
            print(f"  Sent  |  msg-id: {result.get('msg-id')}  |  balance-after: {result.get('balance-after')}")
            if sms.test_mode:
                print("  (test send — check kwtsms.com Queue to confirm; delete to recover credits)")
        else:
            print(f"  Failed: {result.get('code')} — {result.get('description')}")
            sys.exit(1)

    elif cmd == "validate":
        if len(args) < 2:
            print("Usage: kwtsms validate <number> [number2 ...]")
            sys.exit(1)
        report = sms.validate(args[1:])
        print(f"Valid    (OK): {report['ok']}")
        print(f"Invalid  (ER): {report['er']}")
        print(f"No route (NR): {report['nr']}")
        if report.get("error"):
            print(f"Error: {report['error']}")

    else:
        print(f"Unknown command: {cmd}")
        print("Commands: setup | verify | balance | send <mobile> <message> | validate <numbers...>")
        sys.exit(1)


if __name__ == "__main__":
    main()
