import hashlib
import json
import sys
from pathlib import Path
source, http_text, target = sys.argv[1:]
http = int(http_text)
if not 100 <= http <= 599: raise ValueError('Use the actual HTTP status from the saved headers')
source, target = Path(source), Path(target)
raw = source.read_bytes()
report = {'http_status': http, 'source_file': str(source.resolve()), 'source_sha256': hashlib.sha256(raw).hexdigest(),
'network_calls': 0, 'automatic_retry': False, 'next_page_executed': False}
try:
result = json.loads(raw)
except (ValueError, UnicodeDecodeError):
result = None
if http != 200:
report.update(state='http_failure', next_step='Inspect saved HTTP headers and error; do not classify this as an empty search')
elif not isinstance(result, dict):
report.update(state='unreadable_response', next_step='Keep the original bytes; obtain the full direct JSON, not an HTML page or preview')
elif result.get('status') == 'failed' or result.get('error') is not None:
report.update(state='reported_failure', next_step='Inspect the actual error code and request ID before any separately approved retry')
elif result.get('status') != 'succeeded' or result.get('action') != 'twitter.web.fetch_search_timeline':
report.update(state='wrong_response', next_step='Use the successful direct response of twitter.web.fetch_search_timeline')
elif not isinstance(result.get('request_id'), str) or not result['request_id'].strip():
report.update(state='missing_request_id', next_step='Keep the response; source identity is missing')
else:
data = result.get('data')
items = data.get('timeline') if isinstance(data, dict) else None
if not isinstance(items, list):
report.update(state='missing_timeline_array', next_step='Do not substitute an absent or redacted field with []; inspect the original shape')
elif data.get('next_cursor') is not None and not isinstance(data['next_cursor'], str):
report.update(state='invalid_cursor', next_step='Retain the posts but do not invent or follow a cursor')
else:
invalid = []
ids = []
for n, item in enumerate(items):
value = item.get('tweet_id') if isinstance(item, dict) else None
if not isinstance(value, str) or not value.isascii() or not value.isdigit() or not any(c != '0' for c in value):
invalid.append(n)
else:
ids.append(value)
if invalid:
report.update(state='unusable_timeline_ids', invalid_item_indices=invalid, next_step='Keep raw items; a missing, numeric or redacted ID is not an empty result')
else:
report.update(state='empty_timeline' if not items else 'usable_timeline', returned_items=len(items), unique_ids=len(set(ids)),
has_nonblank_cursor=bool((data.get('next_cursor') or '').strip()),
next_step='Review the original phrase and search_type; do not repeat or paginate automatically' if not items else 'Use the saved-page exporter without purchasing page one again')
if isinstance(result, dict):
error = result.get('error')
error = error if isinstance(error, dict) else {}
request_id = result.get('request_id') or error.get('request_id')
if isinstance(request_id, str) and request_id.strip(): report['request_id'] = request_id
if isinstance(error.get('code'), str): report['error_code'] = error['code']
with target.open('x', encoding='utf-8') as f:
json.dump(report, f, ensure_ascii=False, indent=2)
print(report['state'])