#!/usr/bin/env python3
"""Ask a domain whether a machine may hold an account there.

    python3 read.py <domain>
    python3 read.py --url <url>     # read a declaration served somewhere else

Fetches https://<domain>/.well-known/agent-signup.json, validates it with
validate.py, and prints the answer in one line. With no file it says so and
names the agent account index as the fallback. Standard library only.

Exit status: 0 a valid declaration was read; 3 no declaration; 1 a declaration
exists but is invalid or stale, so it was not used.
"""

from __future__ import annotations

import json
import sys
import urllib.error
import urllib.parse
import urllib.request

from validate import USER_AGENT, validate

INDEX_URL = "https://agent-account-index.vercel.app/index.json"
FALLBACK = (
    f"Fallback: the agent account index, mycelium's reading of named services' public terms, "
    f"{INDEX_URL}"
)
ANSWERS = {
    "yes_named_route": "yes, by a named route",
    "no_natural_person_required": "no, a natural person is required",
    "no_automated_signup_forbidden": "no, automated signup is forbidden",
    "unstated": "unstated, which is not permission",
}


def fetch(url: str) -> tuple[int | None, bytes, str]:
    req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=20) as resp:
            return resp.status, resp.read(), resp.geturl()
    except urllib.error.HTTPError as exc:
        return exc.code, b"", url
    except (urllib.error.URLError, OSError) as exc:
        return None, str(exc).encode(), url


def origin_of(url: str) -> str:
    parts = urllib.parse.urlsplit(url)
    return f"{parts.scheme}://{parts.netloc}"


def read(url: str) -> int:
    status, body, final_url = fetch(url)
    if status is None:
        print(f"NO DECLARATION {url}: could not connect ({body.decode(errors='replace')}). {FALLBACK}")
        return 3
    if status != 200:
        print(
            f"NO DECLARATION {url} answered HTTP {status}: this site has not said whether a machine may hold "
            f"an account here, and silence is not permission. {FALLBACK}"
        )
        return 3
    try:
        doc = json.loads(body.decode("utf-8"))
    except (UnicodeDecodeError, json.JSONDecodeError):
        print(
            f"NO DECLARATION {url} answered 200 but not with JSON (likely a catch-all page), so there is no "
            f"declaration here. {FALLBACK}"
        )
        return 3

    problems = validate(doc)
    # A reader ignores fields it does not know (spec section 'Unknown fields'), so an
    # unknown field alone does not stop the answer; any other problem does.
    blocking = [p for p in problems if not p.startswith("E_UNKNOWN_FIELD")]
    if blocking:
        print(f"INVALID DECLARATION {final_url}: {len(blocking)} problem(s), not used. First: {blocking[0]}. {FALLBACK}")
        return 1

    answer = ANSWERS[doc["may_an_agent_hold_an_account"]]
    route = f" ({doc['named_route']})" if doc.get("named_route") else ""
    who = "declared by the service" if doc["declaration_source"] == "service_self_declared" else "a third party's reading, not the service's own word"
    warn = ""
    if doc["origin"] != origin_of(final_url):
        warn += f" WARNING: the file speaks for {doc['origin']} but was served from {origin_of(final_url)}."
    if doc["declaration_source"] == "service_self_declared" and doc["origin"] != origin_of(final_url):
        warn += " A self-declaration served from another origin is not the service's word."
    ignored = len(problems) - len(blocking)
    if ignored:
        warn += f" ({ignored} unknown field(s) ignored.)"
    print(
        f"{doc['service']}: may a machine hold an account? {answer}{route}. Owner of record: "
        f"{doc['owner_of_record'].rstrip('.')}. First credential: {doc['first_credential']['route']}. "
        f"Declared {doc['declared_at']}, expires {doc['expires']}, {who}.{warn}"
    )
    return 0


def main(argv: list[str]) -> int:
    if len(argv) == 3 and argv[1] == "--url":
        return read(argv[2])
    if len(argv) != 2 or argv[1].startswith("-"):
        print("usage: python3 read.py <domain>  |  python3 read.py --url <url>", file=sys.stderr)
        return 2
    domain = argv[1].strip().removeprefix("https://").removeprefix("http://").split("/")[0]
    return read(f"https://{domain}/.well-known/agent-signup.json")


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