#!/usr/bin/env python3
"""Validate an agent-signup.json declaration (spec version 0.1).

    python3 validate.py <file-or-url>

Prints one line per problem, each starting with a named error code, and exits 1
if there are any. Exits 0 and prints a one-line summary if the file is clean.
Standard library only. The vocabulary (required fields, enums) is read from
agent-signup.schema.json beside this file, so the schema and this program
cannot disagree about what a valid value is.
"""

from __future__ import annotations

import datetime as dt
import json
import sys
import urllib.error
import urllib.request
from pathlib import Path

SCHEMA_PATH = Path(__file__).with_name("agent-signup.schema.json")
USER_AGENT = "agent-signup-validator/0.1"


def load_schema() -> dict:
    return json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))


def parse_rfc3339(value: object) -> dt.datetime | None:
    """A full-date (2026-10-15) or a date-time (2026-10-15T20:00:00Z). None if neither."""
    if not isinstance(value, str):
        return None
    text = value.strip()
    try:
        if len(text) == 10:
            return dt.datetime.strptime(text, "%Y-%m-%d").replace(tzinfo=dt.timezone.utc)
        parsed = dt.datetime.fromisoformat(text.replace("Z", "+00:00").replace("z", "+00:00"))
    except ValueError:
        return None
    if parsed.tzinfo is None:
        return None
    return parsed


def resolve(schema: dict, node: dict) -> dict:
    ref = node.get("$ref")
    if ref and ref.startswith("#/$defs/"):
        return schema["$defs"][ref.split("/")[-1]]
    return node


def check_object(schema: dict, obj: dict, spec: dict, where: str, problems: list[str]) -> None:
    props = spec["properties"]
    for name in spec["required"]:
        if name not in obj and name != "declared_at":
            problems.append(f"E_MISSING_REQUIRED {where}{name}: required field is absent")
    for name, value in obj.items():
        if name not in props:
            problems.append(
                f"E_UNKNOWN_FIELD {where}{name}: not defined in spec 0.1; "
                "extensions go under _meta with a reverse-DNS key"
            )
            continue
        rule = resolve(schema, props[name])
        if "enum" in rule and value not in rule["enum"]:
            problems.append(
                f"E_ENUM {where}{name}: {json.dumps(value)} is not one of {', '.join(rule['enum'])}"
            )
        if "const" in rule and value != rule["const"]:
            problems.append(f"E_VERSION {where}{name}: {json.dumps(value)}, this validator reads {rule['const']}")
        if props[name].get("$ref") == "#/$defs/evidence":
            if not isinstance(value, str) or not value.strip():
                problems.append(f"E_EMPTY_EVIDENCE {where}{name}: evidence must be a non-empty string")
        elif props[name].get("$ref") == "#/$defs/https_url" or name == "signup_url":
            if value is not None and not (isinstance(value, str) and value.startswith("https://")):
                problems.append(f"E_URL {where}{name}: {json.dumps(value)} is not an https URL")
        elif rule.get("type") == "string":
            if not isinstance(value, str):
                problems.append(f"E_TYPE {where}{name}: expected a string, got {type(value).__name__}")
            elif rule.get("minLength") and not value.strip():
                problems.append(f"E_EMPTY {where}{name}: must not be empty")
        elif rule.get("type") == "object" and not isinstance(value, dict):
            problems.append(f"E_TYPE {where}{name}: expected an object, got {type(value).__name__}")
        # Every enum has an *_evidence sibling, and it must say something.
        if "enum" in rule and f"{name}_evidence" in props and f"{name}_evidence" not in obj:
            problems.append(f"E_MISSING_EVIDENCE {where}{name}_evidence: the enum {name} has no evidence beside it")


def validate(doc: object) -> list[str]:
    schema = load_schema()
    if not isinstance(doc, dict):
        return [f"E_NOT_OBJECT: the top level is a JSON {type(doc).__name__}, it must be an object"]
    problems: list[str] = []
    check_object(schema, doc, schema, "", problems)

    for name in ("signup_door", "first_credential"):
        value = doc.get(name)
        if isinstance(value, dict):
            check_object(schema, value, schema["$defs"][name], f"{name}.", problems)

    declared = parse_rfc3339(doc.get("declared_at"))
    if "declared_at" not in doc:
        problems.append("E_NO_DATE declared_at: the declaration is not dated")
    elif declared is None:
        problems.append(
            f"E_NO_DATE declared_at: {json.dumps(doc['declared_at'])} is not an RFC 3339 date or date-time with offset"
        )
    expires = parse_rfc3339(doc.get("expires"))
    if "expires" in doc and expires is None:
        problems.append(f"E_BAD_DATE expires: {json.dumps(doc['expires'])} is not an RFC 3339 date or date-time")
    if declared and expires:
        if expires <= declared:
            problems.append("E_DATE_ORDER expires: is not after declared_at")
        if expires < dt.datetime.now(dt.timezone.utc):
            problems.append(f"E_EXPIRED expires: {doc['expires']} has passed; the declaration is stale")

    if doc.get("may_an_agent_hold_an_account") == "yes_named_route":
        route = doc.get("named_route")
        if not (isinstance(route, str) and route.strip()):
            problems.append("E_ROUTE_UNNAMED named_route: the answer is yes_named_route but no route is named")
    elif "named_route" in doc and doc["named_route"] is not None and not isinstance(doc["named_route"], str):
        problems.append("E_TYPE named_route: expected a string or null")

    origin = doc.get("origin")
    if isinstance(origin, str) and not (origin.startswith("https://") and "/" not in origin[len("https://"):]):
        problems.append(f"E_ORIGIN origin: {json.dumps(origin)} must be https://host with no path")

    meta = doc.get("_meta")
    if isinstance(meta, dict):
        for key in meta:
            head = key.split("/", 1)[0]
            if "/" not in key or "." not in head:
                problems.append(f"E_META_KEY _meta.{key}: extension keys are reverse-DNS, e.g. com.example/field")
    return problems


def load(target: str) -> tuple[object | None, str | None]:
    """Return (document, None) or (None, an error line)."""
    try:
        if target.startswith(("https://", "http://")):
            req = urllib.request.Request(target, headers={"User-Agent": USER_AGENT, "Accept": "application/json"})
            with urllib.request.urlopen(req, timeout=20) as resp:
                raw = resp.read()
        else:
            raw = Path(target).read_bytes()
    except urllib.error.HTTPError as exc:
        return None, f"E_FETCH: {target} answered HTTP {exc.code}"
    except (urllib.error.URLError, OSError) as exc:
        return None, f"E_FETCH: {target}: {exc}"
    try:
        return json.loads(raw.decode("utf-8")), None
    except (UnicodeDecodeError, json.JSONDecodeError) as exc:
        return None, f"E_NOT_JSON: {target} is not UTF-8 JSON ({exc})"


def summary(doc: dict) -> str:
    return (
        f"OK {doc['service']} ({doc['origin']}): may_an_agent_hold_an_account={doc['may_an_agent_hold_an_account']}"
        f", named_route={json.dumps(doc.get('named_route'))}, first_credential={doc['first_credential']['route']}"
        f", source={doc['declaration_source']}, expires={doc['expires']}"
    )


def main(argv: list[str]) -> int:
    if len(argv) != 2:
        print("usage: python3 validate.py <file-or-url>", file=sys.stderr)
        return 2
    doc, error = load(argv[1])
    if error:
        print(error)
        return 1
    problems = validate(doc)
    for line in problems:
        print(line)
    if problems:
        return 1
    print(summary(doc))
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv))
