#!/usr/bin/env python3
"""
Manual test script for giveaway system.

Run this to verify giveaway commands work correctly.
"""
import os
import sys
from pathlib import Path

# Use test database
os.environ["DB_PATH"] = "/tmp/test_giveaway.db"

from database import (
    init_db, get_db_path,
    start_giveaway, stop_giveaway,
    is_giveaway_active, get_giveaway_remaining,
    get_giveaway_config, get_or_create_user
)
from token_manager import check_and_grant_giveaway, get_balance

def main():
    db_path = get_db_path()
    print(f"Using database: {db_path}")

    # Initialize
    init_db(db_path)
    print("\n✅ Database initialized")

    # Test 1: Start giveaway
    print("\n" + "="*60)
    print("TEST 1: Start giveaway (10 users, 5 tokens each)")
    print("="*60)
    start_giveaway(tokens=5, users=10, admin_id=12345, db_path=db_path)
    print(f"✅ Giveaway started")
    print(f"   Active: {is_giveaway_active(db_path)}")
    print(f"   Remaining: {get_giveaway_remaining(db_path)}")

    # Test 2: Grant to new users
    print("\n" + "="*60)
    print("TEST 2: Grant tokens to 3 new users")
    print("="*60)
    for i in range(1, 4):
        user_id = 1000 + i
        get_or_create_user(user_id, f"user{i}", f"User{i}", db_path=db_path)
        result = check_and_grant_giveaway(user_id, is_new_user=True, db_path=db_path)
        balance = get_balance(user_id, db_path)
        print(f"User {user_id}: granted={result['granted']}, tokens={result['tokens']}, balance={balance}")

    print(f"\n✅ Remaining slots: {get_giveaway_remaining(db_path)}")

    # Test 3: Try existing user
    print("\n" + "="*60)
    print("TEST 3: Try to grant to existing user")
    print("="*60)
    result = check_and_grant_giveaway(1001, is_new_user=False, db_path=db_path)
    print(f"Result: granted={result['granted']}, reason={result['reason']}")

    # Test 4: Stop giveaway
    print("\n" + "="*60)
    print("TEST 4: Stop giveaway and show stats")
    print("="*60)
    stats = stop_giveaway(db_path)
    print(f"✅ Giveaway stopped")
    print(f"   Users granted: {stats['users_granted']}")
    print(f"   Tokens granted: {stats['tokens_granted']}")
    print(f"   Remaining slots: {stats['remaining_users']}")

    # Test 5: Try when inactive
    print("\n" + "="*60)
    print("TEST 5: Try to grant when giveaway inactive")
    print("="*60)
    get_or_create_user(1005, "inactive_test", "Inactive", db_path=db_path)
    result = check_and_grant_giveaway(1005, is_new_user=True, db_path=db_path)
    print(f"Result: granted={result['granted']}, reason={result['reason']}")

    # Cleanup
    print("\n" + "="*60)
    print("CLEANUP")
    print("="*60)
    try:
        os.unlink(db_path)
        print(f"✅ Removed test database: {db_path}")
    except Exception as e:
        print(f"⚠️ Cleanup warning: {e}")

    print("\n" + "="*60)
    print("ALL TESTS PASSED ✅")
    print("="*60)

if __name__ == "__main__":
    main()
