"""Offline citation-coordinate fixture. Python 3.9+, standard library only.
No network, model calls or file writes. This is application-owned example code.
"""
import hashlib
import sys
import unittest
import unicodedata
from dataclasses import dataclass, replace


def digest(text):
    return hashlib.sha256(text.encode('utf-8')).hexdigest()


@dataclass(frozen=True)
class Citation:
    document_id: str
    representation_sha256: str
    unit: str
    start: int
    end: int
    exact: str


def resolve(document_id, text, citation):
    """Resolve against a trusted, already-authorised text representation."""
    if document_id != citation.document_id:
        raise ValueError('document mismatch')
    if digest(text) != citation.representation_sha256:
        raise ValueError('representation mismatch')
    if type(citation.start) is not int or type(citation.end) is not int:
        raise ValueError('offsets must be integers')
    if citation.unit == 'unicode-code-point':
        source = text
    elif citation.unit == 'utf-8-byte':
        source = text.encode('utf-8')
    else:
        raise ValueError('unsupported offset unit')
    if not 0 <= citation.start < citation.end <= len(source):
        raise ValueError('invalid range')
    if citation.unit == 'utf-8-byte':
        # Validate BOTH boundaries, not only whether the selected bytes decode.
        source[:citation.start].decode('utf-8', errors='strict')
        source[:citation.end].decode('utf-8', errors='strict')
        selected = source[citation.start:citation.end].decode('utf-8', errors='strict')
    else:
        selected = source[citation.start:citation.end]
    if selected != citation.exact:
        raise ValueError('quote mismatch')
    return selected


TEXT = 'Café: deny. Next: allow.'
QUOTE = 'deny'
START = TEXT.encode('utf-8').index(QUOTE.encode('utf-8'))
CITE = Citation('policy-7', digest(TEXT), 'utf-8-byte', START, START + len(QUOTE), QUOTE)


class Tests(unittest.TestCase):
    def test_wrong_slice_is_readable_but_wrong(self):
        self.assertEqual(TEXT[CITE.start:CITE.end], 'eny.')
        self.assertNotEqual(TEXT[CITE.start:CITE.end], QUOTE)

    def test_byte_and_code_point_contracts(self):
        self.assertEqual(resolve('policy-7', TEXT, CITE), QUOTE)
        start = TEXT.index(QUOTE)
        cp = replace(CITE, unit='unicode-code-point', start=start, end=start + len(QUOTE))
        self.assertEqual(resolve('policy-7', TEXT, cp), QUOTE)

    def test_wrong_unit_rejected_by_exact_quote(self):
        with self.assertRaisesRegex(ValueError, 'quote mismatch'):
            resolve('policy-7', TEXT, replace(CITE, unit='unicode-code-point'))

    def test_unknown_unit(self):
        with self.assertRaisesRegex(ValueError, 'unsupported'):
            resolve('policy-7', TEXT, replace(CITE, unit='utf-16-code-unit'))

    def test_changed_representation(self):
        for text in ('Header\n' + TEXT, unicodedata.normalize('NFD', TEXT)):
            with self.subTest(text=text):
                with self.assertRaisesRegex(ValueError, 'representation mismatch'):
                    resolve('policy-7', text, CITE)

    def test_document_identity(self):
        with self.assertRaisesRegex(ValueError, 'document mismatch'):
            resolve('other-policy', TEXT, CITE)

    def test_invalid_ranges_and_types(self):
        for start, end in [(-1, 5), (6, 6), (7, 6), (0, 100), (True, 5), (0, 4.0)]:
            with self.subTest(start=start, end=end):
                with self.assertRaises(ValueError):
                    resolve('policy-7', TEXT, replace(CITE, start=start, end=end))

    def test_multibyte_boundaries(self):
        # UTF-8 encodes é in bytes 3 and 4.
        for start, end in [(4, 5), (3, 4)]:
            with self.subTest(start=start, end=end):
                with self.assertRaises(UnicodeDecodeError):
                    resolve('policy-7', TEXT, replace(CITE, start=start, end=end))

    def test_supplementary_character(self):
        text = '\U0001f512 deny'
        start = text.encode('utf-8').index(b'deny')
        c = Citation('policy-7', digest(text), 'utf-8-byte', start, start + 4, 'deny')
        self.assertEqual(resolve('policy-7', text, c), 'deny')
        self.assertNotEqual(text[start:start + 4], 'deny')

    def test_quote_mismatch(self):
        with self.assertRaisesRegex(ValueError, 'quote mismatch'):
            resolve('policy-7', TEXT, replace(CITE, exact='allow'))


if __name__ == '__main__':
    if sys.argv[1:] == ['--test']:
        unittest.main(argv=[sys.argv[0]], verbosity=2)
    elif sys.argv[1:]:
        raise SystemExit('Usage: python3 rag-citation-offsets.py [--test]')
    else:
        print('UTF-8 byte range:', CITE.start, CITE.end)
        print('Wrong str slice:', repr(TEXT[CITE.start:CITE.end]))
        print('Verified quote:', repr(resolve('policy-7', TEXT, CITE)))
