"""TinkClaw CLI — bot agent commands.

Usage:
    tinkclaw activate <token>    Activate bot on this device
    tinkclaw activate --key <api_key>  Activate with API key directly
    tinkclaw start               Start the bot agent
    tinkclaw status              Show agent status
    tinkclaw stop                Stop the running agent
    tinkclaw logs                Show recent signal log
    tinkclaw config              Show current config
    tinkclaw config set <key> <value>  Update config
    tinkclaw reset               Clear all local data
"""

import argparse
import asyncio
import json
import os
import sys
import time

from .auth import activate_with_token, activate_with_api_key
from .store import MeshStore
from .agent import MeshAgent, STRATEGY_PRESETS


def main():
    parser = argparse.ArgumentParser(
        prog="tinkclaw",
        description="TinkClaw — local-first trading bot",
    )
    sub = parser.add_subparsers(dest="command")

    # activate
    act = sub.add_parser("activate", help="Activate bot on this device")
    act.add_argument("token", nargs="?", help="One-time token from phone")
    act.add_argument("--key", help="API key (alternative to token)")
    act.add_argument("--api-url", default="https://api.tinkclaw.com")
    act.add_argument("--stream-url", default="wss://stream.tinkclaw.com")
    act.add_argument("--name", help="Device name")

    # start
    sub.add_parser("start", help="Start the bot agent")

    # status
    sub.add_parser("status", help="Show agent status")

    # logs
    logs_p = sub.add_parser("logs", help="Show recent signal log")
    logs_p.add_argument("-n", type=int, default=20, help="Number of entries")

    # config
    cfg = sub.add_parser("config", help="Show or update config")
    cfg.add_argument("action", nargs="?", choices=["set", "preset"])
    cfg.add_argument("key", nargs="?")
    cfg.add_argument("value", nargs="?")

    # stop
    sub.add_parser("stop", help="Stop the running agent")

    # reset
    sub.add_parser("reset", help="Clear all local data")

    args = parser.parse_args()

    if not args.command:
        parser.print_help()
        return

    store = MeshStore()

    if args.command == "activate":
        cmd_activate(args, store)
    elif args.command == "start":
        cmd_start(store)
    elif args.command == "status":
        cmd_status(store)
    elif args.command == "logs":
        cmd_logs(args, store)
    elif args.command == "config":
        cmd_config(args, store)
    elif args.command == "stop":
        cmd_stop()
    elif args.command == "reset":
        cmd_reset(store)


def cmd_activate(args, store: MeshStore):
    if not args.token and not args.key:
        print("Error: Provide a one-time token or --key <api_key>")
        print()
        print("  From your phone: TinkClaw > Bot > Add Device > Get Token")
        print("  Then run: tinkclaw activate <token>")
        print()
        print("  Or use your API key directly:")
        print("  tinkclaw activate --key sk-tc-...")
        sys.exit(1)

    print("Activating TinkClaw Bot...")

    try:
        if args.key:
            result = activate_with_api_key(
                args.key,
                api_url=args.api_url,
                device_name=args.name,
            )
        else:
            result = activate_with_token(
                args.token,
                api_url=args.api_url,
                device_name=args.name,
            )
    except RuntimeError as e:
        print(f"Error: {e}")
        sys.exit(1)

    store.device_id = result["device_id"]
    store.auth_token = result.get("auth_token", args.key or "")
    store.api_url = args.api_url
    store.stream_url = args.stream_url

    if result.get("config"):
        store.save_mesh_config(result["config"])

    if args.name:
        store.set("device_name", args.name)

    print()
    print("  Bot activated!")
    print(f"  Device ID: {result['device_id']}")
    print(f"  Stream:    {args.stream_url}")
    print()
    print("  Start the bot:")
    print("    tinkclaw start")
    print()


def cmd_start(store: MeshStore):
    if not store.is_activated():
        print("Error: Device not activated.")
        print("  Run: tinkclaw activate <token>")
        sys.exit(1)

    import logging
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s %(levelname)s %(message)s",
        datefmt="%H:%M:%S",
    )

    agent = MeshAgent(store)
    print("TinkClaw Bot Agent")
    print("=" * 40)
    print(f"Device: {store.get('device_name', 'Unknown')}")
    print(f"Stream: {store.stream_url}")
    print()
    print("Press Ctrl+C to stop")
    print()

    try:
        asyncio.run(agent.start())
    except KeyboardInterrupt:
        print("\nStopping...")


def cmd_status(store: MeshStore):
    if not store.is_activated():
        print("Bot: not activated")
        print("  Run: tinkclaw activate <token>")
        return

    config = store.get_mesh_config()
    print("TinkClaw Bot Status")
    print("=" * 40)
    print(f"Device ID:  {store.device_id}")
    print(f"Device:     {store.get('device_name', 'Unknown')}")
    print(f"API:        {store.api_url}")
    print(f"Stream:     {store.stream_url}")
    print(f"Trades:     {store.trade_count()}")
    print()
    print("Config:")
    print(f"  Strategy:    {config.get('strategy', 'custom')}")
    print(f"  Confidence:  {config.get('confidence', 0.8):.0%}")
    print(f"  Risk:        {config.get('risk_pct', 0.1):.0%}")
    print(f"  Symbols:     {', '.join(config.get('symbols', [])) or 'all'}")
    print(f"  Guardian:    {'on' if config.get('guardian_enabled') else 'off'}")


def cmd_logs(args, store: MeshStore):
    import sqlite3
    conn = sqlite3.connect(store.db_path)
    conn.row_factory = sqlite3.Row
    rows = conn.execute(
        "SELECT * FROM signals ORDER BY received_at DESC LIMIT ?",
        (args.n,),
    ).fetchall()
    conn.close()

    if not rows:
        print("No signals logged yet.")
        return

    print(f"Last {len(rows)} signals:")
    print(f"{'Time':<20} {'Symbol':<12} {'Dir':<5} {'Conf':>5} {'Result':<8} {'Reason'}")
    print("-" * 80)
    for r in reversed(rows):
        t = r["received_at"][:19].replace("T", " ")
        status = "TRADE" if r["accepted"] else "SKIP"
        print(
            f"{t:<20} {r['symbol']:<12} {r['direction']:<5} "
            f"{r['confidence']:>4.0%} {status:<8} {r['reason'] or ''}"
        )


def cmd_config(args, store: MeshStore):
    config = store.get_mesh_config()

    if not args.action:
        print(json.dumps(config, indent=2))
        return

    if args.action == "preset":
        name = (args.key or "").lower()
        if name not in STRATEGY_PRESETS:
            print(f"Available presets: {', '.join(STRATEGY_PRESETS.keys())}")
            return
        preset = STRATEGY_PRESETS[name]
        config["strategy"] = name
        config.update(preset)
        store.save_mesh_config(config)
        print(f"Preset '{name}' applied: confidence={preset['confidence']:.0%} risk={preset['risk_pct']:.0%}")
        return

    if args.action == "set":
        if not args.key or args.value is None:
            print("Usage: tinkclaw config set <key> <value>")
            print("Keys: confidence, risk_pct, symbols, guardian_enabled")
            return

        key = args.key
        value = args.value

        if key == "confidence":
            config["confidence"] = float(value)
        elif key == "risk_pct":
            config["risk_pct"] = float(value)
        elif key == "symbols":
            config["symbols"] = [s.strip() for s in value.split(",") if s.strip()]
        elif key == "guardian_enabled":
            config["guardian_enabled"] = value.lower() in ("true", "1", "yes", "on")
        else:
            print(f"Unknown key: {key}")
            return

        config["strategy"] = "custom"
        store.save_mesh_config(config)
        print(f"Updated: {key} = {config[key]}")


def cmd_stop():
    print("To stop the agent, press Ctrl+C in the terminal running 'tinkclaw start'")
    print("Or kill the process: pkill -f 'tinkclaw start'")


def cmd_reset(store: MeshStore):
    confirm = input("This will delete all local bot data. Continue? [y/N] ")
    if confirm.lower() != "y":
        print("Cancelled.")
        return
    store.clear()
    print("All local bot data cleared.")
    print("Run 'tinkclaw activate <token>' to re-activate.")


if __name__ == "__main__":
    main()
