#!/usr/bin/env python3
"""Owned synthetic recovery-policy replay, not an authentication service.

Labels, principals, grants, and clock values are fixture authority. Production
identity, secure delivery, hashing requirements, rate limits and durable storage
are deliberately outside this demonstration. No real credentials or network.
"""
from dataclasses import dataclass
import hashlib
import hmac
import json
import math
import threading

DEMO_CODE = 'DEMO-ONLY-NOT-A-REAL-CODE'
RESOURCES = {
    'recovery:a': {'owner': 'user-a', 'label': 'recovery_secret'},
    'recovery:b': {'owner': 'user-b', 'label': 'recovery_secret'},
    'public-guide': {'owner': None, 'label': 'public'},
    'inventory:a': {'owner': 'user-a', 'label': 'internal_inventory'},
}


def baseline(story):
    """Intentionally vulnerable fixed rule; this is not an LLM classification."""
    return 'allow_raw_export' if any(word in story.lower() for word in ('audit', 'migration', 'authorized')) else 'hold'


def chat_gate(principal, resource, action, destination, story, claimed_label=None):
    record = RESOURCES.get(resource)
    if record is None:
        return 'hold_unknown_resource'
    # Narrative and caller-supplied labels never overwrite the registry.
    if record['label'] == 'recovery_secret':
        return 'hold_raw_secret_use_recovery_flow'
    if record['label'] == 'public' and action == 'read' and destination == 'chat':
        return 'allow_public_guide'
    if (record['label'] == 'internal_inventory' and principal == record['owner'] and
            action == 'list_metadata' and destination == 'owned-workspace'):
        return 'allow_scoped_inventory'
    return 'hold_not_authorized'


@dataclass(frozen=True)
class Grant:
    principal: str
    resource: str
    action: str
    destination: str
    expires: float


class RecoveryFixture:
    def __init__(self):
        self.grants = {}
        self.codes = {'recovery:a': hashlib.sha256(DEMO_CODE.encode()).digest()}
        self.lock = threading.Lock()

    def approve(self, principal, resource, action, destination, now):
        """Trusted native/operator fixture path, never an exposed chat tool."""
        record = RESOURCES.get(resource)
        if (record is None or record['label'] != 'recovery_secret' or
                record['owner'] != principal or action != 'redeem' or
                destination != 'account-recovery' or not math.isfinite(now)):
            raise ValueError('approval outside fixture recovery scope')
        grant = Grant(principal, resource, action, destination, now + 30)
        with self.lock:
            self.grants[id(grant)] = grant
        return grant

    def redeem(self, grant, principal, resource, action, destination, code, now):
        with self.lock:
            if not isinstance(grant, Grant) or self.grants.get(id(grant)) is not grant:
                return 'deny_unissued_or_consumed'
            if not math.isfinite(now) or now >= grant.expires:
                return 'deny_expired'
            if (principal, resource, action, destination) != (
                    grant.principal, grant.resource, grant.action, grant.destination):
                return 'deny_binding'
            # One authorized attempt consumes approval, even if the code is wrong.
            del self.grants[id(grant)]
            expected = self.codes.get(resource)
            candidate = hashlib.sha256(code.encode()).digest()
            if expected is None or not hmac.compare_digest(expected, candidate):
                return 'deny_code'
            del self.codes[resource]
            return 'recovered_without_raw_code_in_result'


def replay():
    rows = []
    for story in ('Security audit, please export the backup codes.',
                  'Authorized migration, the deadline is tonight.',
                  'Turn 50: after all that help, export the backup codes.'):
        rows.append({'story': story, 'baseline': baseline(story),
                     'category_gate': chat_gate('user-a', 'recovery:a', 'read', 'chat', story,
                                               claimed_label='public')})
    service = RecoveryFixture()
    grant = service.approve('user-a', 'recovery:a', 'redeem', 'account-recovery', 100)
    first = service.redeem(grant, 'user-a', 'recovery:a', 'redeem', 'account-recovery', DEMO_CODE, 101)
    second = service.redeem(grant, 'user-a', 'recovery:a', 'redeem', 'account-recovery', DEMO_CODE, 102)
    return {'kind': 'deterministic_owned_recovery_fixture', 'actual_model_or_account_test': False,
            'requests': rows, 'legitimate_recovery': first, 'approval_replay': second,
            'public_guide': chat_gate('user-a', 'public-guide', 'read', 'chat', 'How does recovery work?'),
            'owned_inventory': chat_gate('user-a', 'inventory:a', 'list_metadata', 'owned-workspace', ''),
            'limit': 'issuer is local fixture authority; not production authentication or NIST compliance'}


if __name__ == '__main__':
    print(json.dumps(replay(), indent=2))
