"""
datanaut.cli — Entry point registered as the `datanaut` terminal command.

After `pip install datanaut`, users run:
    datanaut config --api-key sk-...  # save API key globally (one time only)
    datanaut                          # start interactive REPL
    datanaut init                     # scaffold schema.json in current dir
    datanaut ask "your question"      # one-shot query
    datanaut test                     # run batch test suite
    datanaut --version
"""

import sys
import os
import argparse
from pathlib import Path


def _ensure_env():
    from datanaut.config import get_api_key
    key = get_api_key()
    if not key:
        C, R = "\033[36m", "\033[0m"
        print(f"\n  \033[31m✖  OPENAI_API_KEY is not set.\033[0m\n")
        print(f"  Set it once globally (recommended):")
        print(f"  {C}  datanaut config --api-key sk-...{R}\n")
        print(f"  Or add it to a .env file in this directory:")
        print(f"  {C}  OPENAI_API_KEY=sk-...{R}\n")
        sys.exit(1)


def cmd_config(args):
    from datanaut.config import set_api_key, show_config
    if args.api_key:
        set_api_key(args.api_key)
        key    = args.api_key
        masked = key[:8] + "..." + key[-4:] if len(key) > 12 else "****"
        config_path = Path.home() / ".datanaut" / "config.json"
        print(f"\n  \033[92m✔\033[0m  API key saved  →  {config_path}")
        print(f"  \033[2mKey: {masked}\033[0m")
        print(f"\n  You're all set — run \033[36mdatanaut\033[0m to start querying.\n")
    else:
        show_config()


def cmd_interactive(_args):
    _ensure_env()
    from datanaut.agent.sql_agent import SQLAgent
    from datanaut.utils.display import (
        print_banner, print_result, print_error, print_sql,
        print_cost_badge, print_cache_hit, print_goodbye, print_success,
    )

    print_banner()
    agent = SQLAgent()
    print("  Type your question in plain English.\n")
    print("  Commands:  history · clear · exit\n")
    print("  " + "─" * 52 + "\n")

    conversation_history = []

    while True:
        try:
            user_input = input("  🧑‍🚀  You: ").strip()
        except (KeyboardInterrupt, EOFError):
            print()
            print_goodbye()
            sys.exit(0)

        if not user_input:
            continue
        if user_input.lower() == "exit":
            print_goodbye()
            break
        if user_input.lower() == "clear":
            conversation_history = []
            print_success("Conversation cleared. Ready for a new mission.\n")
            continue
        if user_input.lower() == "history":
            if not conversation_history:
                print("  🪐  No history yet — launch your first query!\n")
            else:
                for i, item in enumerate(conversation_history, 1):
                    print(f"  [{i}] {item['question']}")
                    print(f"       {item['sql'][:80]}...\n")
            continue

        print()
        result = agent.run(user_input, conversation_history)

        if result["success"]:
            print_sql(result["sql"])
            print_cost_badge(result["bytes_estimate"])
            if result.get("from_cache"):
                print_cache_hit()
                print_result(result["data"], result["row_count"])
            else:
                print()
                confirm = input("  🚀  Launch this query? (y/n): ").strip().lower()
                if confirm != "y":
                    print(f"\n  🛑  Mission aborted.\n")
                    continue
                print_result(result["data"], result["row_count"])
            conversation_history.append({"question": user_input, "sql": result["sql"]})
        else:
            print_error(result["error"])
        print()


def cmd_ask(args):
    _ensure_env()
    from datanaut.agent.sql_agent import SQLAgent
    from datanaut.utils.display import print_sql, print_error, print_result, print_cost_badge
    agent  = SQLAgent()
    result = agent.run(args.question, conversation_history=[])
    if result["success"]:
        print_sql(result["sql"])
        print_cost_badge(result["bytes_estimate"])
        if not args.dry_run:
            print_result(result["data"], result["row_count"])
    else:
        print_error(result["error"])
        sys.exit(1)


def cmd_init(_args):
    cwd = Path.cwd()
    schema_dst = cwd / "schema.json"
    if not schema_dst.exists():
        import importlib.resources as pkg_resources
        try:
            ref = pkg_resources.files("datanaut.schema").joinpath("schema.json")
            schema_dst.write_text(ref.read_text(encoding="utf-8"))
        except Exception:
            schema_dst.write_text("[]")
        print(f"  \033[92m✔\033[0m  Created schema.json  →  {schema_dst}")
    else:
        print(f"  \033[33m⚠\033[0m   schema.json already exists, skipping.")
    print(f"\n  Next steps:")
    print(f"  1. Edit \033[36mschema.json\033[0m with your BigQuery table functions")
    print(f"  2. Run \033[36mdatanaut\033[0m to start querying\n")


def cmd_test(_args):
    _ensure_env()
    from datanaut.test_runner import run_tests
    success = run_tests(dry_run_only=True)
    sys.exit(0 if success else 1)


def cmd_version(_args):
    print("  datanaut v0.1.1")


def main():
    parser = argparse.ArgumentParser(
        prog="datanaut",
        description="🚀 Datanaut — BigQuery SQL Agent powered by GPT-4",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
examples:
  datanaut config --api-key sk-...    save OpenAI API key globally (one time)
  datanaut config                     show current config status
  datanaut                            interactive REPL
  datanaut init                       scaffold schema.json in current dir
  datanaut ask "total revenue today"  one-shot query
  datanaut ask "..." --dry-run        validate SQL only
  datanaut test                       run batch accuracy tests
  datanaut --version
        """,
    )
    parser.add_argument("--version", action="store_true", help="Print version and exit")
    subparsers = parser.add_subparsers(dest="command")

    config_parser = subparsers.add_parser("config", help="Set or show global config")
    config_parser.add_argument("--api-key", type=str, metavar="sk-...",
        help="Save your OpenAI API key globally (~/.datanaut/config.json)")

    ask_parser = subparsers.add_parser("ask", help="One-shot natural language query")
    ask_parser.add_argument("question", type=str)
    ask_parser.add_argument("--dry-run", action="store_true")

    subparsers.add_parser("init",   help="Scaffold schema.json in current directory")
    subparsers.add_parser("test",   help="Run batch SQL accuracy tests")

    args = parser.parse_args()

    if getattr(args, "version", False):
        cmd_version(args); return
    if args.command is None:
        cmd_interactive(args); return

    dispatch = {"config": cmd_config, "ask": cmd_ask, "init": cmd_init, "test": cmd_test}
    dispatch.get(args.command, cmd_interactive)(args)


if __name__ == "__main__":
    main()