"""Find an exact synthetic byte marker in explicitly supplied local artifacts."""
import argparse
import hashlib
import json
from pathlib import Path
from tempfile import TemporaryDirectory


def first_offset(path, marker, chunk_size=65536):
    if not isinstance(marker, bytes) or not marker:
        raise ValueError('Expected nonempty marker bytes')
    if type(chunk_size) is not int or chunk_size < 1:
        raise ValueError('Expected positive chunk size')
    path = Path(path)
    if path.is_symlink() or not path.is_file():
        raise ValueError('Expected a regular file, not a symbolic link')
    overlap, position = b'', 0
    with path.open('rb') as source:
        for chunk in iter(lambda: source.read(chunk_size), b''):
            data = overlap + chunk
            index = data.find(marker)
            if index >= 0:
                return position - len(overlap) + index
            overlap = data[-(len(marker) - 1):] if len(marker) > 1 else b''
            position += len(chunk)
    return None


def inspect_artifacts(paths, marker):
    results = []
    for path in paths:
        try:
            offset = first_offset(path, marker)
            results.append(dict(path=str(path), status='found' if offset is not None
                                else 'literal_not_found', first_byte_offset=offset))
        except (OSError, ValueError) as error:
            results.append(dict(path=str(path), status='unavailable',
                                error_type=type(error).__name__))
    return dict(marker_sha256=hashlib.sha256(marker).hexdigest(), artifacts=results,
                deletion_verified=False, transformed_content_checked=False)


def self_test():
    marker = b'GHOST_SYNTHETIC_RETENTION_MARKER'
    with TemporaryDirectory() as folder:
        root = Path(folder)
        cache, cleared = root / 'cache.bin', root / 'cleared.log'
        cache.write_bytes(b'abc' + marker + b'xyz')
        cleared.write_bytes(b'')
        assert first_offset(cache, marker) == 3
        assert first_offset(cache, marker, chunk_size=4) == 3
        assert first_offset(cache, b'a', chunk_size=1) == 0
        assert first_offset(cleared, marker) is None
        assert first_offset(cache, b'not-present') is None
        result = inspect_artifacts([cache, cleared, root / 'missing'], marker)
        assert [r['status'] for r in result['artifacts']] == ['found', 'literal_not_found', 'unavailable']
        assert result['deletion_verified'] is False
        assert result['transformed_content_checked'] is False
        assert result['marker_sha256'] == hashlib.sha256(marker).hexdigest()
        try:
            first_offset(cache, b'')
        except ValueError:
            pass
        else:
            raise AssertionError('Empty marker accepted')
    print('10 synthetic checks passed; no model or external service used')


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--self-test', action='store_true')
    parser.add_argument('--marker', help='Synthetic test marker only, never a real secret')
    parser.add_argument('--files', type=Path, nargs='+')
    args = parser.parse_args()
    if args.self_test:
        self_test()
    elif args.marker and args.files:
        print(json.dumps(inspect_artifacts(args.files, args.marker.encode('utf-8')), indent=2))
    else:
        parser.error('Choose --self-test or --marker TEST_MARKER --files FILE ...')
