"""
Debug script to understand IP access control issue.
"""

import os
import sys
import tempfile
import json
import time
import requests

# Add parent directory to path for imports
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from core.http_server import RateLoaderHTTPServer
from core.ip_manager import IPManager


def main():
    """Debug IP access control issue."""
    print("Debugging IP access control...")
    
    # Create temporary IP manager for testing
    with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
        temp_file = f.name
        json.dump({"global_access": "allowed", "ips": {}}, f)
    
    try:
        ip_manager = IPManager(temp_file)
        server = RateLoaderHTTPServer(port=0)
        server.set_ip_manager(ip_manager)
        
        if server.start():
            port = server.server.server_address[1]
            base_url = f"http://localhost:{port}"
            
            try:
                # Make first request (should be allowed)
                print("Making first request...")
                response = requests.get(f"{base_url}/ping", timeout=5)
                print(f"First request status: {response.status_code}")
                
                # Check IP data
                time.sleep(0.2)
                ips = ip_manager.get_all_ips()
                print(f"IPs after first request: {list(ips['ips'].keys())}")
                print(f"Global mode: {ips['global_access']}")
                
                # Switch to restricted mode
                print("Switching to restricted mode...")
                ip_manager.set_global_access("restricted")
                
                # Check state after switch
                ips = ip_manager.get_all_ips()
                print(f"Global mode after switch: {ips['global_access']}")
                
                # Make second request (should be denied)
                print("Making second request...")
                response = requests.get(f"{base_url}/ping", timeout=5)
                print(f"Second request status: {response.status_code}")
                
                # Check IP data again
                time.sleep(0.2)
                ips = ip_manager.get_all_ips()
                client_ip = "127.0.0.1"
                if client_ip in ips["ips"]:
                    ip_data = ips["ips"][client_ip]
                    print(f"IP data: {ip_data}")
                else:
                    print("IP not found in tracking")
                
            finally:
                server.stop()
        else:
            print("Failed to start server")
            
    except Exception as e:
        print(f"Error: {str(e)}")
        import traceback
        traceback.print_exc()
    finally:
        os.unlink(temp_file)


if __name__ == "__main__":
    main()