import json
import re
from urllib.parse import urlparse, parse_qs

IG_HOST_RE = re.compile(r"(^|\.)instagram\.com$", re.IGNORECASE)
POST_RE = re.compile(r"^/(p|reel|tv)/([A-Za-z0-9_-]+)(?:/|$)", re.IGNORECASE)
PROFILE_RE = re.compile(r"^/([A-Za-z0-9._]+)(?:/|$)")
DIRECT_VIDEO_RE = re.compile(r"^https?://.*\.mp4(?:\?.*)?$", re.IGNORECASE)

def _json(start_response, status, body, origin="*"):
    data = json.dumps(body).encode("utf-8")
    headers = [
        ("Content-Type", "application/json; charset=utf-8"),
        ("Content-Length", str(len(data))),
        ("Access-Control-Allow-Origin", origin),
        ("Access-Control-Allow-Methods", "POST, GET, OPTIONS"),
        ("Access-Control-Allow-Headers", "Content-Type"),
    ]
    start_response(status, headers)
    return [data]

def detect_type(url: str):
    u = (url or "").strip()
    if not u:
        return {"input_type": "unknown"}

    if DIRECT_VIDEO_RE.match(u):
        return {"input_type": "video_url", "media_type": "video", "media_url": u}

    p = urlparse(u)
    host = (p.hostname or "").lower()
    if not IG_HOST_RE.search(host):
        return {"input_type": "unknown"}

    m = POST_RE.match(p.path or "/")
    if m:
        kind = m.group(1).lower()
        code = m.group(2)
        out_type = "post" if kind == "p" else kind
        return {"input_type": out_type, "shortcode": code, "url": u}

    m = PROFILE_RE.match(p.path or "/")
    if m:
        username = m.group(1).strip(".")
        if username and username not in {"explore", "accounts", "reels", "p"}:
            return {"input_type": "profile", "username": username, "url": u}

    return {"input_type": "unknown"}

def application(environ, start_response):
    method = environ.get("REQUEST_METHOD", "GET").upper()
    path = environ.get("PATH_INFO", "") or "/"

    if method == "OPTIONS":
        return _json(start_response, "200 OK", {"ok": True})

    if path == "/health" and method == "GET":
        return _json(start_response, "200 OK", {"ok": True})

    if path == "/api/instagram/resolve" and method == "POST":
        try:
            length = int(environ.get("CONTENT_LENGTH") or "0")
        except ValueError:
            length = 0
        raw = environ["wsgi.input"].read(length) if length > 0 else b"{}"
        try:
            payload = json.loads(raw.decode("utf-8"))
        except Exception:
            return _json(start_response, "400 Bad Request", {"error": "invalid json"})

        url = str(payload.get("url", "")).strip()
        if not url:
            return _json(start_response, "400 Bad Request", {"error": "url is required"})

        result = detect_type(url)
        return _json(start_response, "200 OK", {"original_url": url, "data": result})

    return _json(start_response, "404 Not Found", {"error": "not found"})
