import requests
from typing import List, Tuple

DEFAULT_TARGETS = [
    ("resume_s3", "https://1lzvt4gg70.execute-api.us-west-2.amazonaws.com/manual/Resume_to_S3"),
    ("interview_scheduler", "https://d13x8ut0y2dxy5.cloudfront.net/vapi/"),
    ("auth_url", "https://accounts.google.com/o/oauth2/v2/auth"),
    ("token_endpoint", "https://oauth2.googleapis.com/token"),
    ("gmail_base", "https://gmail.googleapis.com/gmail/v1/users/me"),
    ("screenshotsupload", "https://bd2h456rk7.execute-api.us-west-2.amazonaws.com/manual/interview_screenshots"),
    ("fail_pass", "https://wonoqj9qj4.execute-api.us-west-2.amazonaws.com/prod/interview_insights"),
]

def probe_url(url: str, timeout_s: float = 3.0) -> Tuple[bool, str]:
    last_err = ""
    for method in (requests.head, requests.options, requests.get):
        try:
            r = method(url, timeout=timeout_s)
            if r.status_code < 500:
                try:
                    j = r.json()
                    if isinstance(j, dict) and str(j.get("status", "")).lower() in ("ok", "healthy", "pass"):
                        return True, f"{method.__name__.upper()} {r.status_code} ok"
                except Exception:
                    pass
                return True, f"{method.__name__.upper()} {r.status_code}"
        except Exception as e:
            last_err = str(e)
    return False, f"error: {last_err or 'probe failed'}"

def compute_health(targets: List[tuple]) -> Tuple[int, str, list]:
    healthy, total, unhealthy = 0, 0, []
    for name, url in targets:
        if not url:
            continue
        total += 1
        ok, reason = probe_url(url)
        if ok:
            healthy += 1
            print(f"[HEALTH OK] {name} {url} [{reason}]")
        else:
            unhealthy.append(f"[{name}] {url} [{reason}]")
            print(f"[HEALTH FAIL] {name} {url} [{reason}]")
    if total == 0:
        return 100, "healthy", []
    score = int((healthy / total) * 100)
    condition = "healthy" if score >= 70 else "unhealthy"
    return score, condition, unhealthy

