from flask import Flask, request, jsonify
from flask_cors import CORS
import subprocess, shutil
import re
import os, sys
import requests  # server-side HTTP for RapidAPI proxy

# -------------------------
# Config
# -------------------------
ALLOWED_ORIGINS = os.getenv("ALLOWED_ORIGINS", "*")
SHERLOCK_TIMEOUT = int(os.getenv("SHERLOCK_TIMEOUT", "600"))  # seconds
MAX_USERNAME_LEN = int(os.getenv("MAX_USERNAME_LEN", "30"))

# RapidAPI (set key via systemd env; never hardcode in client)
RAPID_HOST = os.getenv("RAPID_HOST", "sherlock-username-checker.p.rapidapi.com")
RAPID_KEY  = os.getenv("RAPIDAPI_KEY", "")  # REQUIRED for /rapid/check

app = Flask(__name__)

# ---- CORS: let Flask own it; DO NOT set CORS in Apache ----
# Use explicit origins (regex supported via re.compile)
ALLOWED_LIST = [
    re.compile(r"https://.*\.figma\.site"),
    "https://www.figma.com",
    "https://figma.com",
    "https://checkbrandname.com",
    "https://www.checkbrandname.com",
    # Add your own site if you’ll call from there:
    # "https://betterdocs.net",
]

CORS(
    app,
    resources={
        r"/check":   {"origins": ALLOWED_LIST},
        r"/api/*":   {"origins": ALLOWED_LIST},
        r"/rapid/*": {"origins": ALLOWED_LIST},
        r"/health":  {"origins": ALLOWED_LIST},
    },
    methods=["GET", "OPTIONS"],
    allow_headers=["Content-Type", "X-Requested-With", "X-API-Key"],
    supports_credentials=False,
    max_age=86400,
)


# -------------------------
# Helpers
# -------------------------
USERNAME_RE = re.compile(r"^[A-Za-z0-9._-]+$")

def clean_username(raw: str) -> str:
    return (raw or "").strip()

def is_valid_username(name: str) -> bool:
    if not name:
        return False
    if len(name) > MAX_USERNAME_LEN:
        return False
    return bool(USERNAME_RE.match(name))

def extract_urls(text: str) -> list[str]:
    urls = re.findall(r"https?://\S+", text or "")
    cleaned = []
    for u in urls:
        u = u.rstrip(").,;\"'<>")
        if u.startswith(("http://", "https://")):
            cleaned.append(u)
    seen = set()
    ordered = []
    for u in cleaned:
        if u not in seen:
            seen.add(u)
            ordered.append(u)
    return ordered

# -------------------------
# Health
# -------------------------
@app.route("/health", methods=["GET", "HEAD"])
def health():
    return ("", 204)

# -------------------------
# Local Sherlock
# -------------------------
@app.route("/api/check", methods=["GET"])
def check_username():
    username = clean_username(request.args.get("username", ""))

    if not is_valid_username(username):
        return jsonify({"error": "Username is required and must be 1-30 chars [A-Za-z0-9._-]."}), 400

    try:
        command = ["python3", "-m", "sherlock_project.sherlock", "--print-found", username]
        result = subprocess.run(
            command,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            timeout=SHERLOCK_TIMEOUT,
        )

        output = (result.stdout or "") + ("\n" + result.stderr if result.stderr else "")
        urls = extract_urls(output)
        return jsonify({"results": urls}), 200

    except subprocess.TimeoutExpired:
        return jsonify({"error": f"Sherlock timed out after {SHERLOCK_TIMEOUT}s"}), 504
    except Exception as e:
        print(f"[ERROR] /api/check failed: {e}", file=sys.stderr, flush=True)
        return jsonify({"error": "Internal server error"}), 500

# -------------------------
# RapidAPI proxy (browser -> your server -> RapidAPI)
# -------------------------

# -------------------------
# RapidAPI proxy (browser -> your server -> RapidAPI)
# -------------------------
@app.route("/rapid/check", methods=["GET"])
def rapid_check():
    import shutil

    username = clean_username(request.args.get("username", ""))
    if not is_valid_username(username):
        return jsonify({
            "error": "Username is required and must be 1-30 chars [A-Za-z0-9._-]."
        }), 400
    if not RAPID_KEY:
        return jsonify({"error": "RapidAPI not configured on server"}), 503

    host = RAPID_HOST
    url  = f"https://{host}/check?username={username}"

    curl_bin = shutil.which("curl") or "/usr/bin/curl"
    cmd = [
        curl_bin, "-sS", "--fail",
        "-4", "--http1.1",             # ✅ force IPv4 + HTTP/1.1
        "--connect-timeout", "60",     # 10s to connect
        "--max-time", "300",           # 120s total request time
        "-H", f"x-rapidapi-key: {RAPID_KEY}",
        "-H", f"x-rapidapi-host: {host}",
        "-H", "Accept: application/json",
        url,
    ]

    try:
        proc = subprocess.run(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            timeout=300,               # just above --max-time
        )
        if proc.returncode != 0:
            return jsonify({
                "error": "RapidAPI proxy error",
                "detail": proc.stderr.strip(),
                "status": proc.returncode
            }), 502

        # RapidAPI already returns JSON
        return (proc.stdout, 200, {"Content-Type": "application/json"})

    except subprocess.TimeoutExpired:
        return jsonify({"error": "RapidAPI timeout"}), 504
    except Exception as e:
        print(f"[ERROR] /rapid/check (curl) failed: {e}", file=sys.stderr, flush=True)
        return jsonify({"error": "RapidAPI proxy unexpected error"}), 502





# -------------------------
# Dev server (Gunicorn handles in prod)
# -------------------------
if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)
