"""Validate the sample service inventory using the Python standard library."""

import argparse
from collections import deque
import json
from pathlib import Path
import re
import sys
from urllib.parse import urlsplit


SERVICE_FIELDS = {
    "id",
    "owner",
    "runbook",
    "depends_on",
    "recovery_time_minutes",
    "recovery_point_minutes",
}
SERVICE_ID = re.compile(r"[a-z][a-z0-9]*(?:-[a-z0-9]+)*")
RUNBOOK_PATH = re.compile(r"/[a-z0-9-]+(?:/[a-z0-9-]+)*")
MAX_BYTES = 1024 * 1024


def unique_keys(pairs):
    """Reject ambiguity when a JSON object repeats a key."""
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError(f"duplicate JSON key {key!r}")
        result[key] = value
    return result


def reject_constant(value):
    raise ValueError(f"{value} is outside the JSON format")


def valid_runbook(value):
    if not isinstance(value, str) or not value.startswith("https://"):
        return False
    try:
        parts = urlsplit(value)
    except ValueError:
        return False
    return (
        parts.netloc == "runbooks.example.invalid"
        and bool(RUNBOOK_PATH.fullmatch(parts.path))
        and value == f"https://{parts.netloc}{parts.path}"
    )


def validate_inventory(data):
    if not isinstance(data, dict):
        return ["document: expected a JSON object"]

    errors = []
    if data.keys() != {"schema_version", "services"}:
        errors.append("document: expected exactly schema_version and services")
    if type(data.get("schema_version")) is not int or data["schema_version"] != 1:
        errors.append("schema_version: expected the integer 1")

    services = data.get("services")
    if not isinstance(services, list) or not services:
        return errors + ["services: expected a nonempty list"]

    locations = {}
    dependencies = {}
    for index, service in enumerate(services):
        location = f"services[{index}]"
        if not isinstance(service, dict):
            errors.append(f"{location}: expected an object")
            continue
        missing = SERVICE_FIELDS - service.keys()
        extra = service.keys() - SERVICE_FIELDS
        if missing:
            errors.append(f"{location}: missing fields {', '.join(sorted(missing))}")
        if extra:
            errors.append(f"{location}: unexpected fields {', '.join(sorted(extra))}")

        service_id = service.get("id")
        id_ok = isinstance(service_id, str) and bool(SERVICE_ID.fullmatch(service_id))
        if not id_ok:
            errors.append(f"{location}.id: use lowercase letters, digits and hyphens")
        elif service_id in locations:
            errors.append(f"{location}.id: duplicates {locations[service_id]}.id")
            id_ok = False
        else:
            locations[service_id] = location

        owner = service.get("owner")
        if not isinstance(owner, str) or not owner.strip():
            errors.append(f"{location}.owner: enter a nonempty team name")
        if not valid_runbook(service.get("runbook")):
            errors.append(
                f"{location}.runbook: use https://runbooks.example.invalid/ followed by a path"
            )

        links = service.get("depends_on")
        if not isinstance(links, list) or any(
            not isinstance(link, str) or not SERVICE_ID.fullmatch(link) for link in links
        ):
            errors.append(f"{location}.depends_on: expected a list of service IDs")
        elif len(set(links)) != len(links):
            errors.append(f"{location}.depends_on: remove duplicate dependencies")
        elif id_ok:
            dependencies[service_id] = links

        for field, minimum in (("recovery_time_minutes", 1), ("recovery_point_minutes", 0)):
            value = service.get(field)
            if type(value) is not int or value < minimum:
                errors.append(f"{location}.{field}: expected an integer of at least {minimum}")

    for service_id, links in dependencies.items():
        for index, link in enumerate(links):
            field = f"{locations[service_id]}.depends_on[{index}]"
            if link == service_id:
                errors.append(f"{field}: a service cannot depend on itself")
            elif link not in locations:
                errors.append(f"{field}: unknown service ID {link!r}")
    if errors:
        return errors

    # Process dependencies first so cycles can be detected without recursive traversal.
    remaining = {service_id: len(links) for service_id, links in dependencies.items()}
    dependents = {service_id: [] for service_id in dependencies}
    for service_id, links in dependencies.items():
        for link in links:
            dependents[link].append(service_id)
    ready = deque(service_id for service_id, count in remaining.items() if count == 0)
    while ready:
        for dependent in dependents[ready.popleft()]:
            remaining[dependent] -= 1
            if remaining[dependent] == 0:
                ready.append(dependent)
    unresolved = sorted(service_id for service_id, count in remaining.items() if count)
    if unresolved:
        return ["depends_on: a cycle blocks dependency resolution for " + ", ".join(unresolved)]
    return []


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("path", type=Path, help="path to a local UTF-8 JSON file")
    args = parser.parse_args()
    try:
        with args.path.open("rb") as stream:
            raw = stream.read(MAX_BYTES + 1)
        if len(raw) > MAX_BYTES:
            raise ValueError("file exceeds the 1 MiB sample limit")
        data = json.loads(
            raw.decode("utf-8"),
            object_pairs_hook=unique_keys,
            parse_constant=reject_constant,
        )
    except json.JSONDecodeError as error:
        print(
            f"Invalid JSON at line {error.lineno}, column {error.colno}: {error.msg}",
            file=sys.stderr,
        )
        return 2
    except (OSError, UnicodeError, ValueError, RecursionError) as error:
        print(f"Unable to read inventory: {error}", file=sys.stderr)
        return 2

    errors = validate_inventory(data)
    if errors:
        for error in errors:
            print(error, file=sys.stderr)
        return 1

    count = len(data["services"])
    label = "service" if count == 1 else "services"
    print(f"Inventory valid: {count} {label} with resolved dependencies.")
    return 0


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