#!/usr/bin/env python3
"""Read-only literal checks for the accompanying fictional Markdown exercise.

This is not a Markdown parser or a complete technical/linguistic validator.
"""
import argparse
import json
from pathlib import Path
import sys


def check(contract_path, candidate_path):
    contract = json.loads(Path(contract_path).read_text(encoding="utf-8"))
    checks = contract.get("checks")
    if not isinstance(checks, list) or not checks:
        raise ValueError("contract needs a nonempty checks array")
    candidate = Path(candidate_path).read_text(encoding="utf-8-sig")
    labels = set()
    for entry in checks:
        label, literal, expected = entry.get("label"), entry.get("literal"), entry.get("count")
        if (not isinstance(label, str) or not label or label in labels
                or not isinstance(literal, str) or not literal
                or type(expected) is not int or expected < 1):
            raise ValueError("invalid or duplicate contract entry")
        labels.add(label)
        if candidate.count(literal) != expected:
            # Report labels, never contents of potentially private documents.
            raise ValueError(f"{label}: expected literal count {expected}")
    return f"PASS: {len(checks)} declared literal checks (not a complete Markdown review)"


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("contract")
    parser.add_argument("candidate")
    args = parser.parse_args()
    try:
        print(check(args.contract, args.candidate))
    except (OSError, UnicodeError, ValueError, TypeError, AttributeError) as error:
        print(f"CHECK FAILED: {error}", file=sys.stderr)
        return 1
    return 0


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