"""Read-only retention report for the export job store (Stage 4). CLI: export_job_runner retention-report.

It only counts. Nothing here deletes, archives, vacuums or rewrites data; job rows and events are protected by
database triggers that refuse deletion (``export_job_retention_requires_contract``) and stay so until a separate,
approved retention contract. The report answers: how much history exists, how old it is, what the proposed policy
would protect, and what it would make *eligible* (never "to delete").
Importing this module performs no I/O.
"""
from . import export_jobs as jobs

ELIGIBLE_AFTER_DAYS = 400                  # proposal only (see IDBMANAGER_RETENTION_POLICY_PROPOSAL.md)
ELIGIBLE_STATES = ('completed', 'cancelled', 'failed', 'blocked')
PROTECTED_STATES = ('queued', 'running', 'needs_review')
BUCKETS = ((30, 'under_30d'), (90, '30_to_90d'), (ELIGIBLE_AFTER_DAYS, '90d_to_400d'))


def _bucket(age_days):
    for limit, name in BUCKETS:
        if age_days < limit:
            return name
    return 'over_400d'


def report(*, now=None):
    epoch = jobs.clock() if now is None else now
    with jobs._reader(jobs.WORKER_TIMEOUT) as conn:
        rows = conn.execute('''SELECT j.state, j.source, j.kind, CAST((? - strftime('%s', j.created_at)) / 86400 AS INTEGER) AS age,
                                      (SELECT COUNT(*) FROM export_job_events e WHERE e.job_id=j.job_id) AS events,
                                      j.package_id, j.requested_package_id
                               FROM export_jobs j''', (epoch,)).fetchall()
    by_state, by_age, protected, eligible = {}, {}, 0, {'jobs': 0, 'events': 0}
    total_events, packages, requested = 0, set(), 0
    for state, source, kind, age, events, package, wanted in rows:
        by_state[state] = by_state.get(state, 0) + 1
        by_age[_bucket(age)] = by_age.get(_bucket(age), 0) + 1
        total_events += events
        if package:
            packages.add(package)
        if wanted and state in PROTECTED_STATES:
            requested += 1
        if state in PROTECTED_STATES:
            protected += 1
        elif state in ELIGIBLE_STATES and age >= ELIGIBLE_AFTER_DAYS:
            eligible['jobs'] += 1
            eligible['events'] += events
    try:
        storage = jobs.storage_report(events=True)
    except jobs.JobError as exc:
        storage = {'error': exc.code}
    return {
        'read_only': True, 'jobs': len(rows), 'events': total_events, 'by_state': by_state, 'by_age': by_age,
        'protected_never_deletable': {'jobs': protected, 'states': list(PROTECTED_STATES),
                                      'note': 'queued/running/needs_review (UNKNOWN, ACK_REJECTED) and their events'},
        'eligible_under_proposal': dict(eligible, after_days=ELIGIBLE_AFTER_DAYS, states=list(ELIGIBLE_STATES),
                                        note='eligible for archiving and later removal only after a separate approved contract; nothing is removed here'),
        'distinct_packages_referenced_by_jobs': len(packages),
        'active_jobs_requesting_an_existing_package': requested,
        'storage': storage,
    }
