"""Meta App Review submission check for publishing apps (APIWings guide, MIT licence).

Reads a submission plan (what you are about to send to Meta) and lists the problems
Meta's documentation says lead to a rejection. It never calls Meta and it is not an
approval: see "disclaimer" in meta-app-review-rules.json.

Usage: python meta_app_review_check.py submission.json [--json]
Python 3.9 or later, standard library only. Reads meta-app-review-rules.json from the same folder.
Same rules and same results as meta-app-review-check.mjs.
"""

import json
import re
import sys
from datetime import date, datetime, timezone
from pathlib import Path

HERE = Path(__file__).resolve().parent
RULES = json.loads((HERE / "meta-app-review-rules.json").read_text(encoding="utf-8"))


def _is_https(url):
    return isinstance(url, str) and re.match(r"^https://[^\s/]+\.[^\s]+", url.strip(), re.I) is not None


def _norm_text(s):
    return re.sub(r"\s+", " ", str(s or "").lower()).strip()


def _parse(d):
    try:
        s = str(d)
        if len(s) == 10:
            return datetime.strptime(s, "%Y-%m-%d").replace(tzinfo=timezone.utc)
        return datetime.fromisoformat(s.replace("Z", "+00:00"))
    except (TypeError, ValueError):
        return None


def _days_between(a, b):
    x, y = _parse(a), _parse(b)
    if x is None or y is None:
        return None
    if x.tzinfo is None:
        x = x.replace(tzinfo=timezone.utc)
    if y.tzinfo is None:
        y = y.replace(tzinfo=timezone.utc)
    return int((y - x).total_seconds() // 86400)


def canonical_name(name, rules=RULES):
    """Map every spelling Meta uses to the name in the rules."""
    n = str(name or "").strip().lower()
    if n in rules["permissions"]:
        return n, False
    for key, p in rules["permissions"].items():
        if n in p.get("variants", []):
            return key, True
    return n, False


def _finding(code, rules, **extra):
    c = rules["checks"][code]
    out = {"code": code, "level": c["level"], "message": c["message"], "source": rules["sources"][c["source"]]}
    out.update(extra)
    return out


def _verdict(findings):
    if any(f["level"] == "fix_first" for f in findings):
        return "fix_first"
    if any(f["level"] == "review" for f in findings):
        return "review"
    return "no_issues_found"


def check_submission(plan, rules=RULES):
    L = rules["limits"]
    app = plan.get("app") or {}
    t = plan.get("test_instructions") or {}
    subs = plan.get("submissions") or {}
    submitted_on = plan.get("submitted_on") or date.today().isoformat()
    app_findings = []

    def add(code, **extra):
        app_findings.append(_finding(code, rules, **extra))

    if plan.get("audience") == "role_users_only":
        return {
            "result": "not_required",
            "submitted_on": submitted_on,
            "app": [_finding("review_not_required", rules)],
            "permissions": [],
            "disclaimer": rules["disclaimer"],
        }

    # App settings
    if not app.get("business_verified"):
        add("business_not_verified")
    if app.get("purpose") == "own_business":
        add("purpose_mismatch")
    icon = app.get("icon") or {}
    if icon.get("width") != L["icon_px"] or icon.get("height") != L["icon_px"]:
        add("icon_size", found=f"{icon.get('width', '?')}x{icon.get('height', '?')}")
    if icon.get("uses_meta_marks"):
        add("icon_meta_marks")
    if not _is_https(app.get("privacy_policy_url")):
        add("privacy_policy_missing")
    if not _is_https(app.get("terms_url")):
        add("terms_missing")
    dele = app.get("data_deletion") or {}
    if not dele.get("url") or dele.get("type") not in ("callback", "instructions"):
        add("data_deletion_missing")
    elif dele.get("type") == "callback" and not _is_https(dele.get("url")):
        add("data_deletion_not_https")
    if not app.get("category"):
        add("category_missing")
    email = app.get("contact_email")
    if not email or not re.match(r"^[^@\s]+@[^@\s]+\.[^@\s]+$", str(email)):
        add("contact_email_missing")
    if app.get("mode") == "live":
        add("live_mode_before_review")

    # Access for reviewers
    if t.get("app_publicly_accessible") is False:
        add("app_not_accessible")
    if t.get("app_complete") is False:
        add("app_incomplete")
    if t.get("meta_login_works") is False:
        add("login_not_working")
    if t.get("includes_personal_credentials"):
        add("personal_credentials")
    if t.get("uses_fake_account"):
        add("fake_account")
    steps = str(t.get("text") or "").strip()
    if not steps:
        add("test_instructions_missing")
    elif len(steps) < 200:
        add("test_instructions_short", chars=len(steps))
    if t.get("app_has_own_login") and not t.get("app_test_credentials_included"):
        add("own_login_without_credentials")

    # Submission limits
    if subs.get("in_progress_developer", 0) >= L["in_progress_max"]["developer"] or subs.get(
        "in_progress_business", 0
    ) >= L["in_progress_max"]["business"]:
        add("submission_limit_in_progress")
    if subs.get("last_30_days_developer", 0) >= L["rolling_30_days_max"]["developer"] or subs.get(
        "last_30_days_business", 0
    ) >= L["rolling_30_days_max"]["business"]:
        add("submission_limit_30_days")

    # Permissions
    perms = []
    for p in plan.get("permissions") or []:
        name, variant = canonical_name(p.get("name"), rules)
        perms.append(dict(p, name=name, variant=variant, asked=p.get("name")))
    names = {p["name"] for p in perms}
    rp = rules["permissions"]
    logins = {rp[p["name"]]["login"] for p in perms if p["name"] in rp and rp[p["name"]]["network"] == "Instagram"}
    if len(logins) > 1:
        add("mixed_login")
    if any(
        p["name"] in rp
        and rp[p["name"]]["network"] == "Instagram"
        and rp[p["name"]]["login"] == "facebook_login"
        and rp[p["name"]].get("publishes")
        for p in perms
    ):
        add("ppa_reminder")

    desc_count = {}
    for p in perms:
        d = _norm_text(p.get("description"))
        if d:
            desc_count[d] = desc_count.get(d, 0) + 1

    results = []
    for p in perms:
        out = []

        def push(code, **extra):
            out.append(_finding(code, rules, **extra))

        rule = rp.get(p["name"])
        if not rule:
            push("unknown_permission")
        if p["variant"]:
            push("name_variant", use=p["name"])
        for dep in (rule or {}).get("dependencies", []):
            if dep not in names:
                push("missing_dependency", missing=dep)
        if p.get("needed_now") is False:
            push("not_needed_now")

        age = _days_between(p["last_successful_call"], submitted_on) if p.get("last_successful_call") else None
        if age is None or age < 0 or age > L["api_call_window_days"]:
            push("no_recent_api_call", days=age)
        elif age < L["api_call_logging_days"]:
            push("api_call_not_logged_yet", days=age)

        d = _norm_text(p.get("description"))
        if not d:
            push("description_missing")
        else:
            if desc_count.get(d, 0) > 1:
                push("description_duplicate")
            if len(d) < L["description_min_chars_recommended"]:
                push("description_short", chars=len(d))

        r = p.get("recording")
        if not r or r.get("present") is False:
            push("recording_missing")
        else:
            h, w = r.get("height"), r.get("screen_width")
            if isinstance(h, (int, float)) and not isinstance(h, bool) and h < L["recording_min_height_px"]:
                push("recording_resolution", found=h)
            if isinstance(w, (int, float)) and not isinstance(w, bool) and w > L["recording_max_screen_width_px"]:
                push("recording_screen_width", found=w)
            if not r.get("starts_logged_out"):
                push("recording_no_logged_out_start")
            if not r.get("shows_permission_grant"):
                push("recording_no_permission_grant")
            if not r.get("shows_feature_use"):
                push("recording_no_feature_use")
            if r.get("explains_with_audio") and not r.get("captions"):
                push("recording_audio_only")
            if r.get("english_ui") is False and not r.get("captions"):
                push("recording_not_english")
        results.append({"name": p["asked"], "canonical": p["name"], "result": _verdict(out), "findings": out})

    everything = app_findings + [f for p in results for f in p["findings"]]
    return {
        "result": _verdict(everything),
        "submitted_on": submitted_on,
        "app": app_findings,
        "permissions": results,
        "disclaimer": rules["disclaimer"],
    }


def codes_of(report):
    """Every finding code, sorted: what the tests compare."""
    codes = [f["code"] for f in report["app"]]
    for p in report["permissions"]:
        codes += [f"{p['canonical']}:{f['code']}" for f in p["findings"]]
    return sorted(codes)


LABEL = {"fix_first": "FIX FIRST", "review": "REVIEW", "no_issues_found": "NO ISSUES FOUND",
         "not_required": "NOT REQUIRED", "info": "INFO"}


def print_report(report):
    print(f"Result: {LABEL[report['result']]} (planned submission date {report['submitted_on']})")
    for f in report["app"]:
        print(f"  [{LABEL[f['level']]}] app: {f['message']}")
    for p in report["permissions"]:
        print(f"\n{p['name']}: {LABEL[p['result']]}")
        for f in p["findings"]:
            extra = f" (missing {f['missing']})" if f.get("missing") else f" (use {f['use']})" if f.get("use") else ""
            print(f"  [{LABEL[f['level']]}] {f['message']}{extra}")
    print(f"\n{report['disclaimer']}")


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python meta_app_review_check.py submission.json [--json]", file=sys.stderr)
        sys.exit(2)
    rep = check_submission(json.loads(Path(sys.argv[1]).read_text(encoding="utf-8")))
    if "--json" in sys.argv:
        print(json.dumps(rep, indent=2, ensure_ascii=False))
    else:
        print_report(rep)
    sys.exit(1 if rep["result"] == "fix_first" else 0)
