"""Agent post gate: decide whether a post proposed by an AI agent may be published.

Free to use (MIT). From the APIWings guide
https://apiwings.com/blog/ai-agent-publish-social-media-posts

The model proposes; this code decides. No dependencies, Python 3.9 or later.

    from agent_post_gate import check
    result = check(proposal, policy, state)
    result["decision"]  # "publish", "needs_approval" or "blocked"

It checks policy only (kill switch, accounts, approval, links, secrets, mentions, daily budget,
duplicates and network rules). For each network's text and media limits, use the
cross-post validator from https://apiwings.com/blog/post-to-multiple-social-networks-api
"""
import hashlib
import json
import re
from datetime import datetime, timedelta, timezone

URL_RE = re.compile(r"(?:https?://|www\.)[^\s<>\"']+", re.IGNORECASE)
MENTION_RE = re.compile(r"(?<![A-Za-z0-9_@])@[A-Za-z0-9_][A-Za-z0-9_.-]*")
TRAILING = ".,;:!?)]}'\""


def _time(s):
    return datetime.fromisoformat(s.replace("Z", "+00:00")).astimezone(timezone.utc)


def canonical(obj):
    """Canonical JSON: sorted keys, no spaces, UTF-8. Identical in the JavaScript version."""
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)


def sha256(s):
    return hashlib.sha256(s.encode("utf-8")).hexdigest()


def content_of(p):
    """The exact thing a human approves: change one character and the approval no longer matches."""
    return {
        "account_id": p["account_id"],
        "platform": p["platform"],
        "text": p["text"],
        "media": [{"id": m["id"], "alt": m.get("alt") or ""} for m in p.get("media", [])],
        "scheduled_at": p.get("scheduled_at"),
        "options": p.get("options", {}),
        "user_choices": p.get("user_choices", {}),
    }


def approval_hash(p):
    return sha256(canonical(content_of(p)))


def idempotency_key(p):
    """Same draft, same account, same content -> same key, so a retry loop never posts twice."""
    return "agent-" + sha256(p["draft_id"] + "|" + p["account_id"] + "|" + approval_hash(p))[:40]


def links(text):
    out = []
    for m in URL_RE.finditer(text):
        url = m.group(0).rstrip(TRAILING)
        rest = re.sub(r"^(https?://)", "", url, flags=re.IGNORECASE)
        host = re.split(r"[/?#:]", rest, maxsplit=1)[0].lower()
        if host.startswith("www."):
            host = host[4:]
        out.append({"url": url, "host": host})
    return out


def mentions(text):
    return [m.group(0).rstrip(TRAILING) for m in MENTION_RE.finditer(text)]


def normalise(text):
    return re.sub(r"[ \t\n\r]+", " ", text.lower()).strip(" ")


def _domain_allowed(host, domains):
    return any(host == d or host.endswith("." + d) for d in domains)


def check(proposal, policy, state):
    now = _time(state["now"])
    p = proposal
    problems = []
    net_rules = policy.get("network_rules", {}).get(p["platform"], {})
    account = policy.get("accounts", {}).get(p["account_id"])

    # 0. Kill switch: one flag stops every agent post.
    if policy.get("paused"):
        problems.append("posting is paused for all agents (policy.paused)")

    # 1. Only accounts the policy lists, on the network they belong to.
    if account is None:
        problems.append(f"account {p['account_id']} is not in the policy: the agent cannot post there")
    elif account["platform"] != p["platform"]:
        problems.append(f"account {p['account_id']} is a {account['platform']} account, not {p['platform']}")

    if not p["text"].strip() and not p.get("media"):
        problems.append("the post is empty")

    # 2. Links only to allowed domains (stops links injected from pages the agent read).
    domains = [d.lower() for d in policy.get("allowed_link_domains", [])]
    for l in links(p["text"]):
        if not _domain_allowed(l["host"], domains):
            problems.append(f"link to {l['host']} is not on the allowed domains list")

    # 3. Nothing that looks like a secret.
    for name, pattern in policy.get("secret_patterns", {}).items():
        if re.search(pattern, p["text"]):
            problems.append(f"the text contains something that looks like a secret ({name})")

    # 4. Blocked terms (case-insensitive).
    low = p["text"].lower()
    for term in policy.get("blocked_terms", []):
        if term.lower() in low:
            problems.append(f"the text contains the blocked term \"{term}\"")

    # 5. Mentions.
    found = mentions(p["text"])
    limit = policy.get("max_mentions")
    if limit is not None and len(found) > limit:
        problems.append(f"{len(found)} mentions, the policy allows {limit}")

    # 6. Media needs alt text if the policy says so.
    if policy.get("require_alt_text"):
        for m in p.get("media", []):
            if not (m.get("alt") or "").strip():
                problems.append(f"media {m['id']} has no alt text")

    # 7. Scheduled time must be in the future.
    if p.get("scheduled_at") and _time(p["scheduled_at"]) <= now:
        problems.append("scheduled_at is in the past")

    # 8. Network rules: settings the user must choose, and consent.
    for field in net_rules.get("agent_must_not_set", []):
        if field in p.get("options", {}):
            problems.append(f"{p['platform']}: {field} must be chosen by the user, not by the agent")
    for field in net_rules.get("user_must_choose", []):
        if field not in p.get("user_choices", {}):
            problems.append(f"{p['platform']}: the user has not chosen {field} yet")
    if net_rules.get("consent_required") and p.get("user_choices", {}).get("consent") is not True:
        problems.append(f"{p['platform']}: the user has not given explicit consent to post")

    # 9. Daily budget per account (rolling 24 hours) and duplicates.
    history = [h for h in state.get("history", []) if h["account_id"] == p["account_id"]]
    day_ago = now - timedelta(hours=24)
    today = [h for h in history if day_ago < _time(h["published_at"]) <= now]
    budget = policy.get("max_posts_per_account_per_day")
    if budget is not None and len(today) >= budget:
        problems.append(f"daily limit reached: {len(today)} of {budget} posts in the last 24 hours on this account")
    window = now - timedelta(hours=policy.get("duplicate_window_hours", 0))
    norm = normalise(p["text"])
    if norm and any(normalise(h["text"]) == norm and _time(h["published_at"]) > window for h in history):
        problems.append(f"the same text was already posted on this account in the last {policy.get('duplicate_window_hours', 0)} hours")

    h = approval_hash(p)
    result = {
        "decision": "blocked",
        "problems": problems,
        "approval_hash": h,
        "idempotency_key": idempotency_key(p),
    }
    if problems:
        return result

    # 10. Human approval, bound to the exact content.
    required = account.get("approval", "required") == "required" or net_rules.get("approval") == "required"
    if required:
        a = state.get("approval")
        if not a:
            result["decision"] = "needs_approval"
            result["problems"] = ["waiting for a person to approve this exact post"]
            return result
        if a.get("hash") != h:
            result["decision"] = "needs_approval"
            result["problems"] = ["the approval was for a different version of this post: approve it again"]
            return result
        valid = policy.get("approval_valid_hours", 24)
        if _time(a["approved_at"]) + timedelta(hours=valid) < now:
            result["decision"] = "needs_approval"
            result["problems"] = [f"the approval is older than {valid} hours: approve it again"]
            return result
    result["decision"] = "publish"
    return result
