"""
Debug script to understand IP access control issue - fresh start with restricted mode.
"""

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

# 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 with fresh restricted mode."""
    print("Debugging IP access control with fresh restricted mode...")

    # Create temporary IP manager for testing with restricted mode
    with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
        temp_file = f.name
        json.dump({"global_access": "restricted", "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:
                # Check initial state
                ips = ip_manager.get_all_ips()
                print(f"Initial global mode: {ips['global_access']}")
                print(f"Initial IPs: {list(ips['ips'].keys())}")

                # Make first request (should be denied)
                print("Making first request in restricted mode...")
                response = requests.get(f"{base_url}/ping", timeout=5)
                print(f"First request status: {response.status_code}")

                # Check IP data after request
                time.sleep(0.2)
                ips = ip_manager.get_all_ips()
                print(f"IPs after first request: {list(ips['ips'].keys())}")

                if ips["ips"]:
                    client_ip = list(ips["ips"].keys())[0]
                    ip_data = ips["ips"][client_ip]
                    print(f"IP data: {ip_data}")

            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()