"""Portable stdlib-only context and opt-in stderr diagnostics; never writes stdout."""
import json
import os
import re
import secrets
import sys
import time
import uuid
from datetime import datetime, timezone

_started = time.monotonic()

def trace_headers():
    match = re.fullmatch(r'00-([a-f0-9]{32})-([a-f0-9]{16})-[a-f0-9]{2}', os.getenv('AB_TRACEPARENT', ''))
    tid = match[1] if match and match[1] != '0'*32 and match[2] != '0'*16 else secrets.token_hex(16)
    parent = f'00-{tid}-{secrets.token_hex(8)}-01'
    os.environ['AB_TRACEPARENT'] = parent
    os.environ.setdefault('AB_OPERATION_ID', str(uuid.uuid4()))
    return {'traceparent': parent}

def diagnostic(exit_code, kind='none', service='remixmate-studio-cli'):
    if os.getenv('AB_DIAGNOSTICS') != '1':
        return
    trace_headers()
    outcome = 'success' if exit_code == 0 else 'failure' if exit_code == 2 else 'rejected'
    record = dict(schema_version=1, timestamp=datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
        level='error' if outcome == 'failure' else 'info', service=service, environment=os.getenv('APP_ENV', 'dev'),
        event='cli.execution.completed', message='CLI execution completed', outcome=outcome,
        duration_ms=(time.monotonic()-_started)*1000, trace_id=os.environ['AB_TRACEPARENT'].split('-')[1],
        operation_id=os.environ['AB_OPERATION_ID'], attributes={'exit_code': exit_code, 'error_kind': kind if re.fullmatch('[a-z_]{1,80}', str(kind)) else 'unknown'})
    sys.stderr.write('__diagnostic_v1__ ' + json.dumps(record, ensure_ascii=False) + '\n')
    sys.stderr.flush()
