#!/usr/bin/env python3
"""Summarize an audited, pre-merge review ledger. Python standard library only.

This is an open-format evaluation aid, not Weave's scoring implementation.
It consumes supplied assessments and never infers bugs, savings or review quality.
"""
import argparse
from collections import defaultdict
from datetime import datetime
import json
import math


def moment(value):
    t = datetime.fromisoformat(value.replace('Z', '+00:00'))
    if t.tzinfo is None:
        raise ValueError('Timestamps must include a timezone')
    return t


def unique(rows, label):
    ids = [r['id'] for r in rows]
    if len(set(ids)) != len(ids):
        raise ValueError('Duplicate ' + label + ' id')


def number(value, label):
    if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value < 0:
        raise ValueError(label + ' must be finite and nonnegative')
    return value


def divide(n, d):
    return round(n / d, 6) if d else None


def analyze(data):
    if data.get('schema_version') != 1:
        raise ValueError('Expected schema_version 1')
    if not isinstance(data.get('synthetic'), bool):
        raise ValueError('Synthetic must be boolean')
    if not isinstance(data.get('dataset_label'), str) or not data['dataset_label'].strip():
        raise ValueError('Dataset needs a nonempty label')
    start, end = moment(data['period']['start']), moment(data['period']['end_exclusive'])
    if start >= end:
        raise ValueError('Period must have positive duration')
    prs, reviews, comments, costs = [data[k] for k in ('pull_requests', 'reviews', 'comments', 'costs')]
    for rows, name in ((prs, 'PR'), (reviews, 'review'), (comments, 'comment'), (costs, 'cost')):
        unique(rows, name)
    for p in prs:
        if not isinstance(p.get('excluded', False), bool):
            raise ValueError('PR excluded must be boolean')
    pairs = [(r['pr_id'], r['reviewer_id']) for r in reviews]
    if len(set(pairs)) != len(pairs):
        raise ValueError('Consolidate all rounds into one record per PR/reviewer pair')
    for c in costs:
        if not isinstance(c.get('matched_to_review_scope'), bool):
            raise ValueError('Matched cost scope must be boolean')
    pr_by_id = {p['id']: p for p in prs}
    included_prs = {p['id'] for p in prs if p['merged_at'] and start <= moment(p['merged_at']) < end and not p.get('excluded', False)}
    output = defaultdict(lambda: {'reviewer_kind': None, 'review_records': 0, 'output_assessed_records': 0,
                                 'estimated_expert_review_hours': 0, 'suggestions': 0, 'code_addressed_comments': 0,
                                 'reply_addressed_comments': 0, 'unaddressed_comments': 0, 'unknown_comments': 0,
                                 'comments_without_issue_id': 0, 'implemented_issues': set(), 'recorded_cost': 0,
                                 'cost_records': [], 'cost_eligible': True})
    review_by_id = {}
    excluded_reviews = 0
    for r in reviews:
        p = pr_by_id.get(r['pr_id'])
        if p is None:
            raise ValueError('Review refers to unknown PR')
        if r['reviewer_kind'] not in ('human', 'ai'):
            raise ValueError('Invalid reviewer kind')
        if r['pr_id'] not in included_prs or r['reviewer_id'] == p['author_id']:
            excluded_reviews += 1
            continue
        review_by_id[r['id']] = r
        b = output[r['group']]
        if b['reviewer_kind'] not in (None, r['reviewer_kind']):
            raise ValueError('A group cannot mix human and AI reviewers')
        b['reviewer_kind'] = r['reviewer_kind']
        b['review_records'] += 1
        hours = r.get('estimated_expert_review_hours')
        if hours is not None:
            number(hours, 'Estimated expert review hours')
            if not r.get('assessment_source'):
                raise ValueError('Output assessment needs a source')
            b['estimated_expert_review_hours'] += hours
            b['output_assessed_records'] += 1
    all_review_ids = {r['id'] for r in reviews}
    all_issues = set()
    for c in comments:
        if c['review_id'] not in all_review_ids:
            raise ValueError('Comment refers to unknown review')
        r = review_by_id.get(c['review_id'])
        if not r:
            continue
        if c['kind'] not in ('suggestion', 'question', 'praise', 'discussion'):
            raise ValueError('Invalid comment kind')
        if c['kind'] != 'suggestion':
            continue
        p = pr_by_id[r['pr_id']]
        created = moment(c['created_at'])
        # This ledger isolates comments and handling before merge, not post-merge work.
        if created >= moment(p['merged_at']):
            continue
        status = c['resolution']
        if status not in ('code_change', 'reply', 'unaddressed', 'unknown'):
            raise ValueError('Invalid resolution')
        if status in ('code_change', 'reply'):
            if not c.get('evidence_ref') or not c.get('evidence_at'):
                raise ValueError('Addressed suggestion needs evidence and timestamp')
            if not created < moment(c['evidence_at']) < moment(p['merged_at']):
                raise ValueError('Addressing evidence must follow comment and precede merge')
        b = output[r['group']]
        b['suggestions'] += 1
        b[{'code_change': 'code_addressed_comments', 'reply': 'reply_addressed_comments',
           'unaddressed': 'unaddressed_comments', 'unknown': 'unknown_comments'}[status]] += 1
        if not c.get('issue_id'):
            b['comments_without_issue_id'] += 1
        if status == 'code_change' and c.get('issue_id'):
            key = (r['pr_id'], c['issue_id'])
            b['implemented_issues'].add(key)
            all_issues.add(key)
    selected_pools = set()
    skipped_costs = 0
    for cost in costs:
        if not isinstance(cost['selected'], bool):
            raise ValueError('Cost selected must be boolean')
        if not cost['selected']:
            skipped_costs += 1
            continue
        pool = cost['cost_pool_id']
        if pool in selected_pools:
            raise ValueError('Select one authoritative cost record per cost pool')
        selected_pools.add(pool)
        if cost['currency'] != data['currency']:
            raise ValueError('Mixed currency needs prior explicit conversion')
        if cost['scope'] not in ('review_only', 'mixed_use'):
            raise ValueError('Invalid cost scope')
        if cost['fidelity'] not in ('billed', 'estimated', 'configured'):
            raise ValueError('Invalid cost fidelity')
        if not cost.get('evidence_ref'):
            raise ValueError('Cost needs a source')
        if cost['group'] not in output:
            raise ValueError('Cost refers to group without eligible reviews')
        b = output[cost['group']]
        b['recorded_cost'] += number(cost['amount'], 'Cost amount')
        b['cost_records'].append({k: cost[k] for k in ('id', 'cost_pool_id', 'amount', 'scope', 'fidelity', 'evidence_ref', 'matched_to_review_scope')})
        b['cost_eligible'] &= (cost['scope'] == 'review_only' and cost['matched_to_review_scope'] is True)
    groups = {}
    for name, b in sorted(output.items()):
        number(b['estimated_expert_review_hours'], 'Aggregate estimated review hours')
        number(b['recorded_cost'], 'Aggregate recorded cost')
        issues = len(b.pop('implemented_issues'))
        b['unique_implemented_issues'] = issues
        b['estimated_expert_review_hours'] = round(b['estimated_expert_review_hours'], 6)
        b['recorded_cost'] = round(b['recorded_cost'], 6)
        b['addressed_comments'] = b['code_addressed_comments'] + b['reply_addressed_comments']
        b['observed_addressed_fraction_all_suggestions'] = divide(b['addressed_comments'], b['suggestions'])
        b['assessed_resolution_coverage'] = divide(b['suggestions'] - b['unknown_comments'], b['suggestions'])
        b['output_assessment_coverage'] = divide(b['output_assessed_records'], b['review_records'])
        eligible = b.pop('cost_eligible') and bool(b['cost_records']) and b['recorded_cost'] > 0
        b['cost_per_estimated_expert_review_hour'] = divide(b['recorded_cost'], b['estimated_expert_review_hours']) if eligible and b['output_assessed_records'] == b['review_records'] else None
        b['cost_per_unique_implemented_issue'] = divide(b['recorded_cost'], issues) if eligible and not b['comments_without_issue_id'] and not b['unknown_comments'] else None
        groups[name] = b
    return {'schema_version': 1, 'dataset_label': data['dataset_label'], 'synthetic': data['synthetic'],
            'period': data['period'], 'currency': data['currency'], 'included_merged_prs': len(included_prs),
            'excluded_review_records': excluded_reviews, 'unselected_cost_records': skipped_costs,
            'unique_implemented_issues_across_groups': len(all_issues), 'groups': groups,
            'interpretation': [
                'Synthetic examples are not customer results or a vendor ranking.',
                'Estimated expert review hours are supplied assessments, not clocked labor or hours saved.',
                'Addressed includes code changes and clear replies; only the code subset can yield implemented issues.',
                'Issue identity is supplied by the auditor. The script does not infer duplicate findings.',
                'Tool issue counts can overlap and must not be added to get total issues.',
                'No bug recall, severity weighting, causal gain or savings is calculated.',
                'Cost/output requires complete output assessments and declared matching review-only cost; unknown/mixed cost stays visible.',
                'Cost/issue also requires complete issue identifiers and assessed resolution in that group.',
                'Unknown resolution stays in the all-suggestion denominator; inspect coverage alongside the fraction.'
            ]}


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('ledger', help='JSON input following the example ledger')
    parser.add_argument('--output', help='Optional JSON output path; otherwise stdout')
    args = parser.parse_args()
    with open(args.ledger) as f:
        result = analyze(json.load(f))
    rendered = json.dumps(result, indent=2, allow_nan=False) + '\n'
    if args.output:
        with open(args.output, 'w') as f:
            f.write(rendered)
    else:
        print(rendered, end='')
