import argparse
import requests
import json
import sys
import re
import urllib3

from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

API_URL = "https://seon.hackpurgatory.org/search/sync"
USER_AGENT = "hackpurgatory-seonmail/3.0"


def is_valid_email(email: str) -> bool:
    return re.match(r"^[^@]+@[^@]+\.[^@]+$", email) is not None


def build_session(retries: int, insecure: bool, debug: bool):
    session = requests.Session()

    retry_strategy = Retry(
        total=retries,
        backoff_factor=1,
        status_forcelist=[429, 500, 502, 503, 504],
        allowed_methods=["GET"]
    )

    adapter = HTTPAdapter(max_retries=retry_strategy)
    session.mount("https://", adapter)
    session.mount("http://", adapter)

    session.headers.update({
        "User-Agent": USER_AGENT
    })

    if insecure:
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
        if debug:
            print("[DEBUG] SSL verification disabled", file=sys.stderr)

    return session


def main():
    parser = argparse.ArgumentParser(
        prog="hackpurgatory-seonmail",
        description="HackPurgatory SEON Mail API CLI"
    )

    parser.add_argument(
        "-e",
        "--email",
        required=True,
        help="Correo electrónico a consultar"
    )

    parser.add_argument(
        "--timeout",
        type=int,
        default=50,
        help="Timeout HTTP en segundos (default: 20)"
    )

    parser.add_argument(
        "--retries",
        type=int,
        default=2,
        help="Número de reintentos HTTP (default: 2)"
    )

    parser.add_argument(
        "--insecure",
        action="store_true",
        help="Desactivar verificación SSL (self-signed cert)"
    )

    parser.add_argument(
        "--debug",
        action="store_true",
        help="Modo debug"
    )

    args = parser.parse_args()

    if not is_valid_email(args.email):
        print("Email inválido", file=sys.stderr)
        sys.exit(1)

    session = build_session(args.retries, args.insecure, args.debug)

    try:
        if args.debug:
            print(f"[DEBUG] Request -> {API_URL}?value={args.email}", file=sys.stderr)

        response = session.get(
            API_URL,
            params={"value": args.email},
            timeout=args.timeout,
            verify=not args.insecure
        )

        response.raise_for_status()

        data = response.json()
        print(json.dumps(data, indent=2, ensure_ascii=False))

    except requests.RequestException as e:
        print(f"Error HTTP: {e}", file=sys.stderr)
        sys.exit(1)

    except json.JSONDecodeError:
        print("Error al decodificar JSON", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()
