"""CLI entry point for rcl-rlm."""

import argparse
import json
import os
import sys
from pathlib import Path

from .rlm import run_rlm


def get_default_db_path() -> str:
    """Get the default shadow.db path."""
    # Check environment variable first
    if env_path := os.environ.get("SHADOW_DB_PATH"):
        return env_path

    # Default location
    return str(Path.home() / "Library/Application Support/RecallRLM/shadow.db")


def main():
    parser = argparse.ArgumentParser(
        description="Query your iMessage history using RLM (Recursive Language Model)",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  rcl-rlm "What projects did we discuss last month?"
  rcl-rlm "Find messages about dinner plans" --verbose
  rcl-rlm "Who sent me the most messages?" --db /path/to/shadow.db

Environment variables:
  MODELRELAY_API_KEY  - Required. Your ModelRelay API key.
  SHADOW_DB_PATH      - Optional. Path to shadow.db (default: ~/Library/Application Support/RecallRLM/shadow.db)
  RECALL_RLM_MODEL    - Optional. Override default model (gemini-3-flash-preview)
  MODELRELAY_MODEL    - Optional. Alternate env var for model override
""",
    )

    parser.add_argument(
        "question",
        help="The question to ask about your message history",
    )

    parser.add_argument(
        "--db",
        dest="db_path",
        default=get_default_db_path(),
        help="Path to shadow.db SQLite database",
    )

    parser.add_argument(
        "--max-depth",
        type=int,
        default=1,
        help="Maximum recursion depth for llm_query() sub-calls (default: 1)",
    )

    parser.add_argument(
        "--max-calls",
        type=int,
        default=10,
        help="Maximum number of llm_query() sub-calls (default: 10)",
    )

    parser.add_argument(
        "--context",
        dest="conversation_context",
        help="Optional conversation context to provide for follow-up questions",
    )

    parser.add_argument(
        "-v", "--verbose",
        action="store_true",
        help="Show detailed execution trace",
    )

    parser.add_argument(
        "--show-log",
        action="store_true",
        help="Show the full execution log after the answer",
    )

    parser.add_argument(
        "--benchmark",
        action="store_true",
        help="Output JSON with retrieved GUIDs for benchmark comparison",
    )

    args = parser.parse_args()

    # Validate database exists
    if not os.path.exists(args.db_path):
        print(f"Error: Database not found at {args.db_path}", file=sys.stderr)
        print(f"Set SHADOW_DB_PATH or use --db to specify the path.", file=sys.stderr)
        sys.exit(1)

    # Check for API key
    if not os.environ.get("MODELRELAY_API_KEY"):
        print("Error: MODELRELAY_API_KEY environment variable not set", file=sys.stderr)
        sys.exit(1)

    # Run true RLM - single generation with recursive sub-calls
    if not args.benchmark:
        print(f"Searching messages for: {args.question}\n", file=sys.stderr)

    result = run_rlm(
        question=args.question,
        db_path=args.db_path,
        conversation_context=args.conversation_context,
        max_depth=args.max_depth,
        max_calls=args.max_calls,
        verbose=args.verbose and not args.benchmark,
    )

    # Benchmark mode: output JSON with retrieved GUIDs
    if args.benchmark:
        output = {
            "answer": result.answer,
            "retrieved_guids": result.retrieved_guids,
            "iterations": result.iterations,
            "sub_calls_made": result.sub_calls_made,
            "total_tokens": result.total_tokens,
        }
        print(json.dumps(output))
        return

    # Print the answer
    print(result.answer)

    # Print execution log if requested
    if args.show_log:
        print(f"\n{'='*60}", file=sys.stderr)
        print(f"Execution Log ({result.iterations} iterations, {result.sub_calls_made} sub-calls)", file=sys.stderr)
        print(f"{'='*60}", file=sys.stderr)
        for index, entry in enumerate(result.execution_log, start=1):
            print(f"\n--- Iteration {index} ---", file=sys.stderr)
            print(f"Code:\n{entry.get('code', '')}", file=sys.stderr)
            print(f"\nOutput:\n{entry.get('output', '')[:500]}", file=sys.stderr)


if __name__ == "__main__":
    main()
