"""Read supplied report records; does not run Lighthouse or infer search effects."""
import json
from pathlib import Path

def number(value):
    return isinstance(value, (int, float)) and not isinstance(value, bool) and 0 <= value <= 1

def review(report):
    if not isinstance(report, dict):
        return {'state': 'INVALID_REPORT_SHAPE', 'auditScore': None, 'categoryScore': None}
    version = report.get('lighthouseVersion')
    findings = [] if isinstance(version, str) and version.strip() else ['VERSION_BINDING_MISSING']
    category = report.get('categories', {})
    seo = category.get('seo', {}) if isinstance(category, dict) else {}
    category_score = seo.get('score') if isinstance(seo, dict) else None
    audits = report.get('audits', {})
    audit = audits.get('robots-txt') if isinstance(audits, dict) else None
    if not isinstance(audit, dict):
        return {'state': 'AUDIT_RECORD_MISSING', 'version': version, 'auditScore': None,
                'categoryScore': category_score, 'findings': findings}
    mode, score = audit.get('scoreDisplayMode'), audit.get('score')
    if mode == 'error':
        state = 'AUDIT_ERROR_RETAINED'
    elif mode == 'notApplicable':
        state = 'NOT_APPLICABLE_RETAINED'
    elif mode in ('binary', 'numeric') and number(score):
        state = 'SCORED_FAILURE_RECORDED' if score == 0 else 'SCORED_RESULT_RECORDED'
    else:
        state = 'AUDIT_MODE_OR_SCORE_UNSUPPORTED'
    return {'state': state, 'version': version, 'mode': mode, 'auditScore': score,
            'categoryScore': category_score, 'errorMessage': audit.get('errorMessage'),
            'findings': findings, 'upgradeEffectVerified': False,
            'scope': 'Supplied record only; not a Lighthouse run, score calculator or crawler diagnosis'}

if __name__ == '__main__':
    import argparse
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('input', help='Bounded local filled-review.json; no URLs')
    a = p.parse_args()
    with Path(a.input).open('rb') as stream:
        raw = stream.read(1_048_577)
    if len(raw) > 1_048_576:
        p.error('Input exceeds this teaching reader limit of 1 MiB')
    data = json.loads(raw)
    if not isinstance(data, dict) or not isinstance(data.get('records'), list):
        p.error('Expected object containing records array')
    print(json.dumps([{'id': row.get('id'), **review(row.get('suppliedReport'))}
                      for row in data['records'] if isinstance(row, dict)], indent=2))
