import asyncio
import logging
import os
import random
import subprocess
import time

from colorama import Fore, Style, init
from fake_useragent import UserAgent

from src.proxy_handler import scrape_proxies  # Only import scrape_proxies
from src.tools_handler import fetch_dual_engine_results
from src.utils import find_social_profiles, is_potential_forum, extract_mentions

# Suppress InsecureRequestWarning
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# Logging configuration
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

init(autoreset=True)  # Initialize colorama for colored output

DEFAULT_NUM_RESULTS = 500
MAX_RETRY_COUNT = 5

counter_emojis = ['🍻', '📑', '📌', '🌐', '🔰', '💀', '🔍', '📮', 'ℹ️', '📂', '📜', '📋', '📨', '🌟', '💫', '✨', '🔥', '🆔', '🎲']
emoji = random.choice(counter_emojis)  # Select a random emoji for the counter

# Keep track of user inputs
user_inputs = {}

def display_banner():
    print(
        f"""
{Fore.YELLOW} {Fore.WHITE}🇴‌🇲‌🇮‌🇳‌🇮‌🇸‌-🇴‌🇸‌🇮‌🇳‌🇹‌ {Fore.YELLOW}- {Fore.RED}[{Fore.WHITE}Secure Web-Hunter{Fore.RED}]
{Fore.RED} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    {Fore.YELLOW}~ {Fore.CYAN}Developer{Fore.YELLOW}: {Fore.WHITE} AnonCatalyst {Fore.MAGENTA}<{Fore.RED}
    {Fore.RED}------------------------------------------
    {Fore.YELLOW}~ {Fore.CYAN}Github{Fore.YELLOW}:{Fore.BLUE} https://github.com/AnonCatalyst/{Fore.RED}
    {Fore.RED}------------------------------------------
    {Fore.YELLOW}~ {Fore.CYAN}Instagram{Fore.YELLOW}:{Fore.BLUE} https://www.instagram.com/istoleyourbutter/{Fore.RED}
    """)

async def get_user_input(prompt, options=None):
    clear_screen()
    
    # Display the banner
    display_banner()
    
    # Display current input statistics
    print(f'{Fore.RED}_' * 80)
    print(f"{Fore.RED}Input Statistics:{Fore.WHITE}")
    for key, value in user_inputs.items():
        print(f"{Fore.YELLOW}{key}: {Fore.WHITE}{value}")

    if options:
        print(f"\n{Fore.RED}Options (examples):{Fore.WHITE}")
        for option in options:
            print(f" - {option}")

    user_input = input(f"\n{Fore.RED}[{Fore.YELLOW}!{Fore.RED}]{Fore.WHITE} {prompt}: {Fore.WHITE}")
    
    # Save input
    user_inputs[prompt] = user_input
    
    print(f"{Fore.RED}You entered: {Fore.WHITE}{user_input}\n")
    await asyncio.sleep(1)  # Short delay to let user see the prompt

    return user_input

async def main():
    clear_screen()
    display_banner()
    await asyncio.sleep(2)  # Delay to let user read the information

    query = await get_user_input("Enter the query to search")
    # Language and country parameters are now informational only
    language = await get_user_input("Enter language code (optional)", ["e.g., en (English)", "e.g., es (Spanish)", "e.g., fr (French)", "e.g., de (German)"])
    country = await get_user_input("Enter country code (optional)", ["e.g., US (United States)", "e.g., CA (Canada)", "e.g., GB (United Kingdom)", "e.g., AU (Australia)"])
    start_date = await get_user_input("Enter start date (YYYY-MM-DD)")
    end_date = await get_user_input("Enter end date (YYYY-MM-DD)")

    # Validate and format date_range
    date_range = (start_date, end_date)

    # Proceed with scraping and validation
    print(f'{Fore.RED}_' * 80)
    print(f" {Fore.RED}[{Fore.GREEN}+{Fore.RED}]{Fore.WHITE} Beginning proxy harvesting operation{Fore.RED}.{Fore.WHITE}\n")
    
    start_time = time.time()
    proxies = await scrape_proxies()
    
    if not proxies:
        logger.error(f" {Fore.RED}No proxies scraped. Exiting...{Style.RESET_ALL}")
        return
    else:
        print(f"✨ Total proxies harvested: {Fore.GREEN}{len(proxies)}{Style.RESET_ALL}")
        print(f" {Fore.RED}[{Fore.GREEN}+{Fore.RED}]{Fore.WHITE} Beginning ghost validation of proxies{Fore.RED}.{Fore.WHITE}\n")
    
    # Load valid proxies from file (generated by proxy_handler)
    try:
        with open("config/valid_proxies.txt", "r") as f:
            valid_proxies = [line.strip() for line in f.readlines()]
            logger.info(f" >| {Fore.GREEN}Loaded {len(valid_proxies)} validated proxies{Fore.RED}.{Fore.WHITE}\n")
    except FileNotFoundError:
        logger.error(f" {Fore.RED}No valid proxies found. Exiting...{Fore.WHITE}")
        return

    # Updated function call with new parameters
    await fetch_dual_engine_results(
        query, 
        language=language, 
        country=country, 
        date_range=date_range, 
        proxies=valid_proxies
    )
    await asyncio.sleep(3)  # Introduce delay between requests

    subprocess.run(["python3", "-m", "src.usr", query])

def clear_screen():
    os.system('cls' if os.name == 'nt' else 'clear')

if __name__ == "__main__":
    asyncio.run(main())
