"""Offline newsroom exposure checks; supplied bytes only, no discovery requests."""
import json
import re
from urllib.parse import urlsplit


def certificate_names(records, domain):
    domain = domain.lower().rstrip(".")
    if not re.fullmatch(r"[a-z0-9-]+(?:\.[a-z0-9-]+)+", domain):
        raise ValueError("Expected DNS domain")
    names = set()
    for record in records:
        for value in record.get("name_value", "").splitlines():
            name = value.lower().rstrip(".")
            if name.startswith("*."):
                continue
            if re.fullmatch(r"[a-z0-9-]+(?:\.[a-z0-9-]+)+", name):
                if name == domain or name.endswith("." + domain):
                    names.add(name)
    return sorted(names)


def inspect_feed_text(text):
    terms = ("DRAFT", "EMBARGO", "[INTERNAL]", "DO NOT PUBLISH", "CONFIDENTIAL")
    return [term for term in terms if term in text.upper()]


def classify_draft_response(status, body):
    if status != 200:
        return "not_demonstrated"
    try:
        records = json.loads(body)
    except (ValueError, TypeError):
        return "invalid_response"
    if not isinstance(records, list):
        return "not_a_post_list"
    exposed = [item["id"] for item in records if isinstance(item, dict)
               and item.get("status") == "draft"
               and type(item.get("id")) is int
               and isinstance(item.get("content"), dict)
               and isinstance(item["content"].get("rendered"), str)]
    return {"draft_ids_in_supplied_response": exposed}


def replay():
    names = certificate_names([
        {"name_value": "origin.newsroom.example\n*.newsroom.example"},
        {"name_value": "newsroom.example.evil.invalid\nORIGIN.NEWSROOM.EXAMPLE"},
    ], "newsroom.example")
    assert names == ["origin.newsroom.example"]
    assert inspect_feed_text("Embargo: synthetic fixture") == ["EMBARGO"]
    assert inspect_feed_text("Published story") == []
    assert classify_draft_response(403, "[]") == "not_demonstrated"
    assert classify_draft_response(200, '{"code":"rest_forbidden"}') == "not_a_post_list"
    assert classify_draft_response(200, "[]") == {"draft_ids_in_supplied_response": []}
    draft = [{"id": 7, "status": "draft", "content": {"rendered": "OWNED FIXTURE"}}]
    result = classify_draft_response(200, json.dumps(draft))
    assert result == {"draft_ids_in_supplied_response": [7]}
    assert classify_draft_response(200, "<html>login</html>") == "invalid_response"
    return {"assertions": 8, "certificate_candidates": names, "draft_fixture": result,
            "scope": "Supplied fixtures only. Certificate names are not origins; markers are not proof of a leak."}


if __name__ == "__main__":
    print(json.dumps(replay(), indent=2))
