import copy
import json
import unittest
from pathlib import Path
from compare import compare


class ComparisonContract(unittest.TestCase):
    def setUp(self):
        self.data = json.loads(Path(__file__).with_name('synthetic-example.json').read_text())
        self.a, self.b = self.data['before'], self.data['after']

    def test_noncanonical_date_cannot_invert_chronology(self):
        self.a['sourceDate'] = '2026-10-03'
        self.b['sourceDate'] = '20261002'
        with self.assertRaises(ValueError):
            compare(self.a, self.b)

    def test_basic_and_week_dates_are_rejected(self):
        for value in ['20261002', '2026-W40-5']:
            with self.subTest(value=value):
                self.b['sourceDate'] = value
                with self.assertRaises(ValueError):
                    compare(self.a, self.b)

    def test_missing_is_not_zero(self):
        result = compare(self.a, self.b)
        cov = result['coverage']['nonBrand']['after']
        self.assertEqual(cov['denominator'], 5)
        self.assertEqual(cov['unknown'], 1)
        self.assertEqual(cov['topN']['10']['observedAtLeast'], 3)
        self.assertEqual(cov['topN']['10']['possibleAtMost'], 4)
        self.assertIsNone(cov['topN']['10']['count'])
        self.assertIsNone(cov['topN']['10']['rate'])

    def test_nested_threshold_entries_and_exits(self):
        t = compare(self.a, self.b)['thresholdTransitions']
        self.assertEqual(t['3']['exits'], ['n1'])
        self.assertEqual(t['5']['entries'], ['n5'])
        self.assertEqual(t['10']['entries'], ['n2'])
        self.assertEqual(t['100']['entries'], ['n3'])
        self.assertEqual(t['3']['unknownComparisons'], ['n4'])

    def test_zero_rank_rejected(self):
        self.b['rows'][0]['position'] = 0
        with self.assertRaises(ValueError):
            compare(self.a, self.b)

    def test_float_or_boolean_rank_rejected(self):
        for value in [1.2, True, '1', 101]:
            with self.subTest(value=value):
                self.b['rows'][0]['position'] = value
                with self.assertRaises(ValueError):
                    compare(self.a, self.b)

    def test_duplicate_rows_rejected(self):
        self.b['rows'].append(copy.deepcopy(self.b['rows'][0]))
        with self.assertRaises(ValueError):
            compare(self.a, self.b)

    def test_missing_row_blocks_cohort_comparison(self):
        self.b['rows'].pop()
        self.assertEqual(compare(self.a, self.b)['status'], 'INCOMPARABLE')

    def test_same_id_changed_keyword_rejected(self):
        self.b['rows'][0]['keyword'] = 'A different keyword'
        self.assertEqual(compare(self.a, self.b)['status'], 'INCOMPARABLE')

    def test_each_condition_change_blocks_comparison(self):
        for key in self.b['conditions']:
            b = copy.deepcopy(self.b)
            b['conditions'][key] += '-changed'
            with self.subTest(key=key):
                self.assertEqual(compare(self.a, b)['status'], 'INCOMPARABLE')

    def test_no_unranked_movement_imputed(self):
        r = next(x for x in compare(self.a, self.b)['movements'] if x['id'] == 'n3')
        self.assertIsNone(r['positionsImproved'])
        self.assertIsNone(r['urlChanged'])

    def test_changed_brand_classification_blocked(self):
        self.b['rows'][0]['brand'] = False
        self.assertEqual(compare(self.a, self.b)['status'], 'INCOMPARABLE')

    def test_row_order_is_not_identity(self):
        original = compare(self.a, self.b)
        self.b['rows'].reverse()
        self.assertEqual(compare(self.a, self.b), original)

    def test_same_or_reverse_date_blocked(self):
        for day in ['2026-10-01', '2026-09-30']:
            self.b['sourceDate'] = day
            self.assertEqual(compare(self.a, self.b)['status'], 'INCOMPARABLE')

    def test_actual_destination_change_is_separate(self):
        self.b['rows'][1]['url'] = 'https://example.invalid/replacement/'
        r = next(x for x in compare(self.a, self.b)['movements'] if x['id'] == 'n1')
        self.assertEqual(r['positionsImproved'], -2)
        self.assertTrue(r['urlChanged'])

    def test_unknown_to_ranked_not_proven_entry(self):
        self.b['rows'][4].update(status='ranked', position=1, url='https://example.invalid/n4/')
        t = compare(self.a, self.b)['thresholdTransitions']['3']
        self.assertNotIn('n4', t['entries'])
        self.assertIn('n4', t['unknownComparisons'])


if __name__ == '__main__':
    unittest.main()
