#!/usr/bin/env python3
"""Same-shape JSON exercise: keys, types, list lengths and simple {{tokens}}.

No network, SDK, grammar check, ICU parser or general i18next validation.
Catalogues needing different target-language plural keys require another schema.
"""
import json
import re
import sys
from collections import Counter

TOKEN = re.compile(r"\{\{[A-Za-z_][A-Za-z0-9_]*\}\}")


def load(path):
    def unique(pairs):
        result = {}
        for key, value in pairs:
            if key in result:
                raise ValueError(f"duplicate object key: {key}")
            result[key] = value
        return result
    def invalid_constant(value):
        raise ValueError(f"not a JSON constant: {value}")
    with open(path, encoding="utf-8") as stream:
        return json.load(stream, object_pairs_hook=unique,
                         parse_constant=invalid_constant)


def check(source, target, path="$", findings=None):
    findings = [] if findings is None else findings
    if type(source) is not type(target):
        findings.append(f"{path}: type changed")
    elif isinstance(source, dict):
        for key in sorted(source.keys() - target.keys()):
            findings.append(f"{path}[{key!r}]: missing key")
        for key in sorted(target.keys() - source.keys()):
            findings.append(f"{path}[{key!r}]: unexpected key")
        for key in source.keys() & target.keys():
            check(source[key], target[key], f"{path}[{key!r}]", findings)
    elif isinstance(source, list):
        if len(source) != len(target):
            findings.append(f"{path}: list length changed")
        for i, (before, after) in enumerate(zip(source, target)):
            check(before, after, f"{path}[{i}]", findings)
    elif isinstance(source, str):
        for label, text in [("source", source), ("target", target)]:
            remaining = TOKEN.sub("", text)
            if "{" in remaining or "}" in remaining:
                findings.append(f"{path}: unsupported {label} brace syntax; use a format parser")
        if Counter(TOKEN.findall(source)) != Counter(TOKEN.findall(target)):
            findings.append(f"{path}: placeholder mismatch")
        if source and not target.strip():
            findings.append(f"{path}: empty target")
    elif source != target:
        findings.append(f"{path}: non-text value changed")
    return findings


def main():
    if len(sys.argv) != 3:
        print("Usage: python3 validate.py source.json candidate.json", file=sys.stderr)
        return 2
    try:
        findings = sorted(check(load(sys.argv[1]), load(sys.argv[2])))
    except (OSError, ValueError) as error:
        print(f"INPUT ERROR: {error}", file=sys.stderr)
        return 2
    for finding in findings:
        print(finding)
    print(f"{len(findings)} structural finding(s). Language and runtime review still required.")
    return 1 if findings else 0


if __name__ == "__main__":
    raise SystemExit(main())
