#!/usr/bin/env python3
import sys
import subprocess
import argparse
from pathlib import Path

def print_header(msg):
    print(f"\n{'='*50}\n{msg}\n{'='*50}")

def run_pytest(args):
    cmd = [sys.executable, "-m", "pytest"]
    cmd.extend(args)
    
    print(f"Running: {' '.join(cmd)}")
    return subprocess.call(cmd)

def main():
    parser = argparse.ArgumentParser(description="Butler Test Runner")
    parser.add_argument("--unit", action="store_true", default=True, help="Run fast unit tests (default)")
    parser.add_argument("--live", action="store_true", help="Run integration tests with REAL LLM (Costs $)")
    parser.add_argument("--all", action="store_true", help="Run all tests")
    
    args = parser.parse_args()
    
    # Project root
    root = Path(__file__).parent.parent
    sys.path.insert(0, str(root))

    failed = False

    # 1. Unit Tests
    if args.unit or args.all:
        print_header("Phase 1: Unit Tests (Fast & Free)")
        # Ignore live_llm marker
        ret = run_pytest(["tests/unit", "-m", "not live_llm", "-v"])
        if ret != 0:
            failed = True
            print("❌ Unit tests failed!")
            if not args.all:
                sys.exit(ret)

    # 2. Live Tests
    if args.live or args.all:
        print_header("Phase 2: Live Integration Tests (REAL API CALLS)")
        print("⚠️  Warning: This will consume API credits!")
        
        # We need to ensure we run the integration folder
        ret = run_pytest(["tests/integration", "-m", "live_llm", "-v"])
        if ret != 0:
            failed = True
            print("❌ Live tests failed!")

    if failed:
        sys.exit(1)
    else:
        print_header("✅ All Tests Passed!")

if __name__ == "__main__":
    main()
