import os
import re
import sys
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib.parse import urlparse
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

# Terminal Colors
GREEN = "\033[92m"
RED = "\033[91m"
YELLOW = "\033[93m"
CYAN = "\033[96m"
RESET = "\033[0m"

# MAIN SETTINGS
MAX_WORKERS = 20  # Number of websites scanned concurrently at the same time
TIMEOUT = 5       # Request timeout in seconds for high speed


def print_banner():
    print(f"{CYAN}=================================================={RESET}")
    print(f"{GREEN}          WP Version Checker                      {RESET}")
    print(f"{CYAN} Coded by Lagger - ManadoGhost | https://manadoghost.cc {RESET}")
    print(f"{CYAN}=================================================={RESET}\n")


def create_session():
    """Creates an HTTP session with adapter connection pooling for maximum speed."""
    session = requests.Session()
    retries = Retry(total=1, backoff_factor=0.1, status_forcelist=[500, 502, 503, 504])
    session.mount("http://", HTTPAdapter(max_retries=retries, pool_connections=50, pool_maxsize=50))
    session.mount("https://", HTTPAdapter(max_retries=retries, pool_connections=50, pool_maxsize=50))
    return session


def normalize_url(url):
    url = url.strip()
    if not url:
        return None
    if not url.startswith(("http://", "https://")):
        url = "https://" + url
    return url


def check_wordpress_single(session, url):
    headers = {
        "User-Agent": (
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
        )
    }

    try:
        response = session.get(url, headers=headers, timeout=TIMEOUT, allow_redirects=True)
        html = response.text

        match = re.search(
            r'<meta\s+name=["\']generator["\']\s+content=["\']WordPress\s*([0-9.]+)["\']',
            html,
            re.IGNORECASE,
        )

        if match:
            return True, f"WordPress {match.group(1)}", url

        if "wp-content" in html or "wp-includes" in html:
            return True, "WordPress (Version hidden)", url

        return False, "Not WP", url

    except:
        if url.startswith("https://"):
            try:
                fallback_url = url.replace("https://", "http://", 1)
                response = session.get(
                    fallback_url,
                    headers=headers,
                    timeout=TIMEOUT,
                    allow_redirects=True,
                )
                html = response.text
                match = re.search(
                    r'<meta\s+name=["\']generator["\']\s+content=["\']WordPress\s*([0-9.]+)["\']',
                    html,
                    re.IGNORECASE,
                )
                if match:
                    return True, f"WordPress {match.group(1)}", fallback_url
                if "wp-content" in html or "wp-includes" in html:
                    return True, "WordPress (Version hidden)", fallback_url
            except:
                pass

        return False, "Not WP", url


def worker_task(target):
    session = create_session()
    url = normalize_url(target)
    if not url:
        return None
    return check_wordpress_single(session, url)


def main():
    print_banner()

    if not os.path.exists("list.txt"):
        print(f"{RED}[!] list.txt not found! Please create the file first.{RESET}")
        return

    # Read file and remove duplicate URLs automatically
    with open("list.txt", "r") as f:
        urls = list(set([line.strip() for line in f if line.strip()]))

    total_url = len(urls)
    if total_url == 0:
        print(f"{RED}[!] list.txt is empty!{RESET}")
        return

    print(f"{CYAN}[*] Starting scan for {total_url} unique websites using {MAX_WORKERS} concurrent threads...{RESET}\n")

    wp_list = []
    completed = 0

    try:
        with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
            futures = {executor.submit(worker_task, target): target for target in urls}

            for future in as_completed(futures):
                completed += 1
                result = future.result()
                if not result:
                    continue

                is_wp, info, final_url = result
                original_target = futures[future]

                if is_wp:
                    print(f"[{GREEN}WP{RESET}] ({completed}/{total_url}) {final_url} --> {GREEN}{info}{RESET}")
                    wp_list.append(f"{final_url}\n")
                else:
                    print(f"[{RED}NOT WP{RESET}] ({completed}/{total_url}) {original_target} --> {RED}{info}{RESET}")

    except KeyboardInterrupt:
        print(f"\n{RED}[!] Process stopped by user (Ctrl+C).{RESET}")

    # Save results
    if wp_list:
        with open("hasil_wp.txt", "w") as f:
            f.writelines(wp_list)
        print(f"\n{GREEN}[+] Complete! Found {len(wp_list)} WordPress websites.{RESET}")
        print(f"{CYAN}[+] Pure URLs successfully saved to: hasil_wp.txt{RESET}")
    else:
        print(f"\n{YELLOW}[-] No WordPress websites were found from the list.{RESET}")


if __name__ == "__main__":
    main()