"""Bounded RAG experiment: authored rankings and claims, real local checks.

The score fixtures are not embeddings. The claim verifier is a narrow rule
checker, not an entailment model or an evaluation of free-form prose.
"""
import json
from dataclasses import dataclass


@dataclass(frozen=True)
class Chunk:
    id: str
    tenant: str
    group: str
    version: int
    valid_from: int
    valid_to: int
    policy: str
    text: str


CORPUS = (
    Chunk('returns-v1-base', 'tenant-a', 'retail', 1, 0, 100, 'returns', 'Old policy: unused products may be returned within 60 days.'),
    Chunk('returns-v2-base', 'tenant-a', 'retail', 2, 100, 300, 'returns', 'Current policy: unused products may be returned within 30 days. Product exceptions apply.'),
    Chunk('returns-v2-exception', 'tenant-a', 'retail', 2, 100, 300, 'returns', 'Opened batteries cannot be returned unless defective, even within 30 days.'),
    Chunk('returns-v3-base', 'tenant-a', 'retail', 3, 300, 999, 'returns', 'Future policy: unused products may be returned within 45 days.'),
    Chunk('tenant-b-base', 'tenant-b', 'retail', 2, 100, 300, 'returns', 'A different tenant accepts returns within 90 days.'),
)
INDEX = {chunk.id: chunk for chunk in CORPUS}
AUTHORED_VECTOR_ORDER = ['tenant-b-base', 'returns-v1-base', 'returns-v2-base', 'returns-v3-base', 'returns-v2-exception']
AUTHORED_LEXICAL_ORDER = ['returns-v2-base', 'returns-v2-exception', 'tenant-b-base', 'returns-v1-base', 'returns-v3-base']
FACTS = {'product': 'battery', 'opened': True, 'defective': False, 'age_days': 20}


def eligible(chunk, tenant, groups, at):
    return chunk.tenant == tenant and chunk.group in groups and chunk.valid_from <= at < chunk.valid_to


def rrf(rankings, k=60):
    scores = {}
    for ranking in rankings:
        if len(ranking) != len(set(ranking)):
            raise ValueError('duplicate_rank_id')
        for rank, item_id in enumerate(ranking, 1):
            scores[item_id] = scores.get(item_id, 0) + 1 / (k + rank)
    return [i for i, _ in sorted(scores.items(), key=lambda pair: (-pair[1], pair[0]))]


def assemble(tenant='tenant-a', groups=('retail',), at=150, budget=300, include_exception=True):
    allowed = {c.id for c in CORPUS if eligible(c, tenant, groups, at)}
    rankings = [[i for i in ranking if i in allowed] for ranking in (AUTHORED_VECTOR_ORDER, AUTHORED_LEXICAL_ORDER)]
    fused = rrf(rankings)
    selected = fused[:1]
    expanded = list(selected)
    if selected and include_exception:
        seed = INDEX[selected[0]]
        # Expansion repeats the authorization/time checks. Do not fetch a raw parent by ID.
        for c in CORPUS:
            if c.id in allowed and c.policy == seed.policy and c.version == seed.version and c.id not in expanded:
                expanded.append(c.id)
    chars = sum(len(INDEX[i].text) for i in expanded)
    # Preserve the complete bundle or abstain. Never silently truncate the exception.
    assembled = expanded if chars <= budget else []
    return {'query': 'opened battery return at 20 days', 'tenant': tenant, 'at': at,
            'eligible_ids': sorted(allowed), 'rankings': rankings, 'fused_ids': fused,
            'selected_ids': selected, 'expanded_ids': expanded, 'required_chars': chars,
            'budget_chars': budget, 'assembled_ids': assembled,
            'assembly_status': 'budget_exceeded' if expanded and not assembled else ('assembled' if assembled else 'no_evidence'),
            'context': [{'id': i, 'version': INDEX[i].version, 'text': INDEX[i].text} for i in assembled]}


def verify_claims(answer, trace, facts=FACTS):
    if type(answer) is not dict or set(answer) != {'claims'} or type(answer['claims']) is not list or not answer['claims']:
        return {'accepted': False, 'reason': 'answer_shape'}
    assembled = set(trace['assembled_ids'])
    if not assembled:
        return {'accepted': False, 'reason': 'no_assembled_evidence'}
    for claim in answer['claims']:
        if type(claim) is not dict or set(claim) != {'field', 'value', 'citations'}:
            return {'accepted': False, 'reason': 'claim_shape'}
        citations = claim['citations']
        if type(citations) is not list or not citations or any(type(i) is not str or i not in assembled for i in citations):
            return {'accepted': False, 'reason': 'citation_not_in_context'}
        if claim['field'] == 'eligible':
            required = {'returns-v2-base'}
            if facts['product'] == 'battery' and facts['opened']:
                required.add('returns-v2-exception')
            if not required.issubset(citations):
                return {'accepted': False, 'reason': 'missing_required_evidence'}
            expected = facts['age_days'] <= 30 and (not facts['opened'] or facts['defective'])
            if type(claim['value']) is not bool or claim['value'] != expected:
                return {'accepted': False, 'reason': 'claim_contradicted'}
        elif claim['field'] == 'window_days':
            if 'returns-v2-base' not in citations or type(claim['value']) is not int or claim['value'] != 30:
                return {'accepted': False, 'reason': 'claim_contradicted'}
        else:
            return {'accepted': False, 'reason': 'unsupported_claim_field'}
    return {'accepted': True, 'reason': 'bounded_rules_supported', 'semantic_prose': 'not_scored'}


def candidate(value=False, citations=None):
    return {'claims': [{'field': 'eligible', 'value': value,
                        'citations': citations if citations is not None else ['returns-v2-base', 'returns-v2-exception']}]}


def demo():
    broken = assemble(include_exception=False)
    fixed = assemble()
    short = assemble(budget=100)
    denied = assemble(groups=())
    return {'origin': 'authored_rankings_claims_local_rules',
            'failure': {'trace': broken, 'candidate': candidate(True, ['returns-v2-base']),
                        'verdict': verify_claims(candidate(True, ['returns-v2-base']), broken)},
            'repair': {'trace': fixed, 'candidate': candidate(), 'verdict': verify_claims(candidate(), fixed)},
            'present_citation_wrong_claim': verify_claims(candidate(True), fixed),
            'budget_failure': {'trace': short, 'verdict': verify_claims(candidate(), short)},
            'permission_failure': {'trace': denied, 'verdict': verify_claims(candidate(), denied)},
            'boundary': 'No embedding inference, model generation, arbitrary prose entailment, or live ACL update is tested.'}


if __name__ == '__main__':
    print(json.dumps(demo(), indent=2, sort_keys=True))
