import re
import threading
import time
from collections import deque
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import urldefrag, urljoin, urlparse

import requests
from bs4 import BeautifulSoup

HEADERS = {
    "User-Agent": (
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
        "AppleWebKit/537.36 Chrome/124.0 Safari/537.36"
    ),
    "Cache-Control": "no-cache, no-store, must-revalidate",
    "Pragma": "no-cache",
    "Expires": "0",
}

TIMEOUT = 8
MAX_WORKERS = 15  # Número de solicitudes simultáneas para máxima velocidad
MAX_PAGES = 5000

lock = threading.Lock()


def normalizar_url(url):
    url, _ = urldefrag(url)
    parsed = urlparse(url)
    path = parsed.path
    if path != "/":
        path = path.rstrip("/")
    return parsed._replace(
        scheme=parsed.scheme.lower(), netloc=parsed.netloc.lower(), path=path
    ).geturl()


def es_enlace_interno(url, dominio):
    parsed = urlparse(url)
    return parsed.scheme in ("http", "https") and parsed.netloc.lower() == dominio


def extraer_enlaces(html, url_actual, dominio):
    soup = BeautifulSoup(html, "html.parser")
    enlaces = set()

    for tag in soup.find_all("a", href=True):
        href = tag.get("href", "").strip()
        if not href or href.startswith(
            ("mailto:", "tel:", "javascript:", "data:", "#")
        ):
            continue
        url = normalizar_url(urljoin(url_actual, href))
        if es_enlace_interno(url, dominio):
            enlaces.add(url)

    patrones = [
        r'window\.location\.href\s*=\s*[\'"]([^\'"]+)[\'"]',
        r'window\.location\s*=\s*[\'"]([^\'"]+)[\'"]',
    ]
    for patron in patrones:
        for href in re.findall(patron, html, re.IGNORECASE):
            url = normalizar_url(urljoin(url_actual, href))
            if es_enlace_interno(url, dominio):
                enlaces.add(url)

    return enlaces


def procesar_url(session, url, dominio):
    params_anti_cache = {"_nocache": int(time.time() * 1000)}
    try:
        response = session.get(
            url, allow_redirects=False, timeout=TIMEOUT, params=params_anti_cache
        )
        status = response.status_code
        content_type = response.headers.get("Content-Type", "").lower()

        nuevos_enlaces = set()
        destino_301 = None

        if status == 200 and "text/html" in content_type:
            nuevos_enlaces = extraer_enlaces(response.text, url, dominio)
        elif status in (301, 302, 307, 308):
            destino = response.headers.get("Location", "Desconocido")
            destino_301 = normalizar_url(urljoin(url, destino))
            if es_enlace_interno(destino_301, dominio):
                nuevos_enlaces.add(destino_301)

        return url, status, nuevos_enlaces, destino_301, None

    except requests.exceptions.RequestException as e:
        return url, "ERROR", set(), None, str(e)


def auditar_sitio(url_base):
    url_base = normalizar_url(url_base)
    dominio = urlparse(url_base).netloc.lower()

    session = requests.Session()
    session.headers.update(HEADERS)

    pendientes = deque([url_base])
    visitadas = set()
    todos_los_enlaces = set()

    # Clasificación específica de resultados
    urls_301 = []  # Lista de dicts con origen y destino
    urls_404 = []  # Lista de URLs 404
    otros_errores = []

    print("=" * 70)
    print("🚀 INICIANDO AUDITORÍA OPTIMIZADA (MULTI-THREADING + ANTI-CACHE)")
    print("=" * 70)
    print(f"🌐 Sitio: {url_base} | Dominio: {dominio} | Hilos: {MAX_WORKERS}\n")

    with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
        while (pendientes or executor._work_queue.qsize() > 0) and len(
            visitadas
        ) < MAX_PAGES:
            lote = []

            with lock:
                while pendientes and len(lote) < MAX_WORKERS:
                    u = pendientes.popleft()
                    if u not in visitadas:
                        visitadas.add(u)
                        lote.append(u)

            if not lote:
                time.sleep(0.1)
                continue

            # Procesar bloque de URLs en paralelo
            futures = [
                executor.submit(procesar_url, session, url, dominio) for url in lote
            ]

            for future in futures:
                url, status, nuevos, destino, err = future.result()

                with lock:
                    todos_los_enlaces.update(nuevos)

                    if status == 200:
                        print(f"  ✅ [200 OK] {url}")
                    elif status == 301:
                        print(f"  ⚠️ [301 REDIRECT] {url} → {destino}")
                        urls_301.append({"origen": url, "destino": destino})
                    elif status == 404:
                        print(f"  ❌ [404 NOT FOUND] {url}")
                        urls_404.append(url)
                    elif status == "ERROR":
                        print(f"  ❌ [CONEXIÓN FALLIDA] {url}: {err}")
                        otros_errores.append({"url": url, "error": err})
                    else:
                        print(f"  ℹ️ [{status}] {url}")

                    # Agregar nuevos enlaces no visitados a la cola
                    for n in nuevos:
                        if n not in visitadas and n not in pendientes:
                            pendientes.append(n)

    # ========================================================
    # REPORTE FINAL DE RESULTADOS
    # ========================================================
    print("\n" + "=" * 70)
    print("📊 RESUMEN EJECUTIVO DE AUDITORÍA")
    print("=" * 70)
    print(f"📄 Total de páginas analizadas: {len(visitadas)}")
    print(f"🔗 Total de enlaces únicos descubiertos: {len(todos_los_enlaces)}")
    print(f"⚠️ Total de URLs con estado 301: {len(urls_301)}")
    print(f"❌ Total de URLs con estado 404: {len(urls_404)}")
    print(f"⚠️ Otros errores / Conexiones fallidas: {len(otros_errores)}")

    print("\n" + "=" * 70)
    print(f"⚠️ DETALLE DE URLs CON REDIRECCIÓN 301 ({len(urls_301)})")
    print("=" * 70)
    if urls_301:
        for idx, r in enumerate(urls_301, 1):
            print(f"{idx}. {r['origen']}\n   → {r['destino']}")
    else:
        print("🎉 ¡Felicidades! No se encontraron URLs con estado 301.")

    print("\n" + "=" * 70)
    print(f"❌ DETALLE DE URLs CON ERROR 404 ({len(urls_404)})")
    print("=" * 70)
    if urls_404:
        for idx, url in enumerate(urls_404, 1):
            print(f"{idx}. {url}")
    else:
        print("🎉 ¡Felicidades! No se encontraron enlaces rotos 404.")

    return {
        "visitadas": visitadas,
        "urls_301": urls_301,
        "urls_404": urls_404,
        "errores": otros_errores,
    }


# Ejecución principal
resultado = auditar_sitio("https://www.logicbus.com.mx/")
