#!/usr/bin/env python3
"""Offline parser-disagreement fixture. No tool execution or network access."""
import json
import sys
import unittest

PAYLOAD = '{"environment":"staging","environment":"production"}'


def first_wins(pairs):
    """Deliberately unsafe preview policy for the demonstration."""
    result = {}
    for name, value in pairs:
        if name not in result:
            result[name] = value
    return result


def unique_object(pairs):
    result = {}
    for name, value in pairs:
        if name in result:
            raise ValueError("Duplicate JSON member")
        result[name] = value
    return result


def reject_constant(value):
    raise ValueError("Non-JSON numeric constant")


def decode_arguments(raw):
    """Reject duplicates at every object depth before creating a mapping.

    This bounded teaching decoder is not a complete production validator.
    Apply transport byte/depth limits and operation-specific validation too.
    """
    value = json.loads(raw, object_pairs_hook=unique_object,
                       parse_constant=reject_constant)
    if not isinstance(value, dict):
        raise ValueError("Tool arguments must be an object")
    return value


def validate_demo_schema(value):
    if set(value) != {"environment"}:
        raise ValueError("Unexpected fields")
    if value["environment"] not in ("staging", "production"):
        raise ValueError("Invalid environment")
    return value


class DecoderTests(unittest.TestCase):
    def test_preview_executor_disagreement(self):
        self.assertEqual(json.loads(PAYLOAD, object_pairs_hook=first_wins),
                         {"environment": "staging"})
        self.assertEqual(json.loads(PAYLOAD), {"environment": "production"})

    def test_both_decoded_values_pass_schema(self):
        for kwargs in ({}, {"object_pairs_hook": first_wins}):
            self.assertEqual(set(validate_demo_schema(json.loads(PAYLOAD, **kwargs))),
                             {"environment"})

    def test_reject_top_level_duplicate(self):
        with self.assertRaises(ValueError):
            decode_arguments(PAYLOAD)

    def test_reject_identical_duplicate_values(self):
        with self.assertRaises(ValueError):
            decode_arguments('{"x":1,"x":1}')

    def test_reject_nested_duplicate(self):
        with self.assertRaises(ValueError):
            decode_arguments('{"target":{"env":"a","env":"b"}}')

    def test_reject_duplicate_in_array_object(self):
        with self.assertRaises(ValueError):
            decode_arguments('{"items":[{"id":1,"id":2}]}')

    def test_reject_escaped_equivalent_name(self):
        with self.assertRaises(ValueError):
            decode_arguments(r'{"environment":"staging","\u0065nvironment":"production"}')

    def test_same_name_in_separate_objects_is_allowed(self):
        value = {"items": [{"id": 1}, {"id": 2}]}
        self.assertEqual(decode_arguments(json.dumps(value)), value)

    def test_unique_input_round_trip(self):
        value = {"target": {"environment": "staging"}, "ids": [2, 1]}
        self.assertEqual(decode_arguments(json.dumps(value)), value)

    def test_reject_non_object_root(self):
        for raw in ('[]', 'null', 'true', '1', '"x"'):
            with self.subTest(raw=raw), self.assertRaises(ValueError):
                decode_arguments(raw)

    def test_reject_non_json_constants(self):
        for raw in ('{"x":NaN}', '{"x":Infinity}', '{"x":-Infinity}'):
            with self.subTest(raw=raw), self.assertRaises(ValueError):
                decode_arguments(raw)

    def test_reject_malformed_and_trailing_input(self):
        for raw in ('{"x":}', '{"x":1} {"x":2}'):
            with self.subTest(raw=raw), self.assertRaises(ValueError):
                decode_arguments(raw)


if __name__ == "__main__":
    if sys.argv[1:] == ["--test"]:
        unittest.main(argv=[sys.argv[0]], verbosity=2)
    elif sys.argv[1:]:
        raise SystemExit("Usage: agent-tool-duplicate-json.py [--test]")
    else:
        print("preview:", json.loads(PAYLOAD, object_pairs_hook=first_wins)["environment"])
        print("executor:", json.loads(PAYLOAD)["environment"])
        for kwargs in ({"object_pairs_hook": first_wins}, {}):
            validate_demo_schema(json.loads(PAYLOAD, **kwargs))
        print("schema: both decoded objects pass")
        try:
            decode_arguments(PAYLOAD)
        except ValueError as error:
            print("strict decoder:", error)
        else:
            raise SystemExit("ERROR: ambiguous payload accepted")
