"""Analyzes R8 keep rule radius JSON output and computes optimization scores."""

import json
import os
import sys


def rule_origin(origin, file_origins, maven_coordinates):
  """Returns the file, line and Maven coordinate a keep rule comes from."""
  origin = origin or {}
  file_origin = file_origins.get(origin.get('file_origin_id'), {})
  filename = file_origin.get('filename', '')
  if os.path.isabs(filename):
    try:
      relative = os.path.relpath(os.path.realpath(filename))
    except ValueError:  # On Windows, a file on another drive.
      relative = '..'
    if relative != '..' and not relative.startswith('..' + os.sep):
      filename = relative
  coordinate = file_origin.get('maven_coordinate') or {}
  if coordinate and not coordinate.get('artifact_id'):
    coordinate = maven_coordinates.get(coordinate.get('id'), {})
  maven = ':'.join(
      coordinate[k]
      for k in ('group_id', 'artifact_id', 'version')
      if coordinate.get(k)
  )
  return {
      'file': filename,
      'line': origin.get('line_number'),
      'maven_coordinate': maven or None,
      'provided_by_build_system': bool(
          file_origin.get('provided_by_build_system')
      ),
  }


def describe_rule(entry, file_origins, maven_coordinates):
  """Returns a rule's source text, origin, and whether the app can edit it."""
  origin = rule_origin(entry.get('origin'), file_origins, maven_coordinates)
  # Dumps written with the R8 system property have no Maven coordinates, and R8
  # doesn't mark the AGP default files as provided by the build system, so the
  # file path decides as well.
  path = origin['file'].replace(os.sep, '/')
  if origin['maven_coordinate']:
    comes_from = origin['maven_coordinate']
  elif '/transformed/' in path:
    comes_from = 'library rules in ' + path.split('/transformed/', 1)[1]
  elif (
      origin['provided_by_build_system']
      or 'default_proguard_files' in path
      or path.startswith('Android Gradle plugin')
  ):
    comes_from = 'AGP defaults'
  elif (
      '/intermediates/generated_proguard_file/' in path
      or '/intermediates/aapt_proguard_file/' in path
  ):
    comes_from = 'generated by the build (' + path + ')'
  else:
    comes_from = None
  return {
      'source': entry.get('source'),
      'origin': origin,
      'in_app_files': comes_from is None,
      'from': comes_from,
  }


def analyze(json_path, output_dir=None):
  """Computes R8 optimization scores and rule impacts from keep radius JSON."""
  if os.path.isdir(json_path):
    json_path = os.path.join(json_path, 'keepruleradius.json')
  if output_dir is None:
    output_dir = os.path.dirname(json_path) or 'tmp/keepradius'
  try:
    with open(json_path, 'r', encoding='utf-8') as f:
      d = json.load(f)
  except (OSError, ValueError, TypeError) as e:
    print(f'Error loading JSON: {e}', file=sys.stderr)
    sys.exit(1)

  c_map = {
      c.get('id'): set(c.get('constraints', []))
      for c in d.get('keep_constraints_table', [])
  }
  r_map = {
      r.get('id'): c_map.get(r.get('constraints_id'), set())
      for r in d.get('keep_rule_blast_radius_table', [])
  }

  tot_opt = tot_obf = tot_shr = tot_items = 0

  for tbl in (
      'kept_class_info_table',
      'kept_field_info_table',
      'kept_method_info_table',
  ):
    for i in d.get(tbl, []):
      tot_items += 1
      kb = i.get('kept_by', [])
      if any('DONT_OPTIMIZE' in r_map.get(r, set()) for r in kb):
        tot_opt += 1
      if any('DONT_OBFUSCATE' in r_map.get(r, set()) for r in kb):
        tot_obf += 1
      if any('DONT_SHRINK' in r_map.get(r, set()) for r in kb):
        tot_shr += 1

  bi = d.get('build_info', {})
  live = sum(
      int(bi.get(k, 0))
      for k in ('live_class_count', 'live_field_count', 'live_method_count')
  )
  denom = live if live > 0 else tot_items

  globals_src = [
      g.get('source', '').lower()
      for g in d.get('global_keep_rule_blast_radius_table', [])
  ]

  def score(cnt, flag):
    if any(flag in src for src in globals_src):
      return 0.0
    return max(0.0, 100.0 - ((cnt / denom * 100) if denom > 0 else 0))

  opt_score = score(tot_opt, '-dontoptimize')
  obf_score = score(tot_obf, '-dontobfuscate')
  shr_score = score(tot_shr, '-dontshrink')

  result = [
      f'Optimization Score: {opt_score:.2f}%',
      f'Obfuscation Score:  {obf_score:.2f}%',
      f'Shrinking Score:    {shr_score:.2f}%',
  ]
  for line in result:
    print(line)

  file_origins = {f.get('id'): f for f in d.get('file_origin_table', [])}
  maven_coordinates = {
      m.get('id'): m for m in d.get('maven_coordinate_table', [])
  }
  rules = {
      r.get('id'): describe_rule(r, file_origins, maven_coordinates)
      for r in d.get('keep_rule_blast_radius_table', [])
  }

  processed = []
  type_map = {
      t.get('id'): t.get('java_descriptor', '')
      for t in d.get('type_reference_table', [])
  }

  class_id_to_name = {}
  for c in d.get('kept_class_info_table', []):
    type_id = c.get('class_reference_id')
    name = type_map.get(type_id, f'Class#{type_id}')
    class_id_to_name[c.get('id')] = name

  for r in d.get('keep_rule_blast_radius_table', []):
    br = r.get('blast_radius', {})
    c_list = br.get('class_blast_radius', [])
    f_list = br.get('field_blast_radius', [])
    m_list = br.get('method_blast_radius', [])
    c, f, m = len(c_list), len(f_list), len(m_list)
    impact = c + f + m
    if impact == 0:
      continue
    impact_pct = (impact / denom * 100) if denom > 0 else 0.0

    example_classes = [
        class_id_to_name.get(cid, f'Class#{cid}') for cid in c_list[:5]
    ]

    processed.append({
        'id': r.get('id'),
        **rules[r.get('id')],
        'impact': impact,
        'impact_pct': f'{impact_pct:.2f}%',
        'classes': c,
        'fields': f,
        'methods': m,
        'example_classes': example_classes,
        'subsumed_by': list(br.get('subsumed_by', [])),
    })

  processed.sort(key=lambda x: x['impact'], reverse=True)

  # Rules that keep exactly the same items list each other in subsumed_by,
  # because R8 checks both directions with a non-strict subset test. Treat each
  # such group as identical rules: keep one of them (a rule in the app's own
  # files first, then the lowest id) and list the others as identical to it.
  by_id = {r['id']: r for r in processed}
  groups = {}
  for r in processed:
    for sid in r['subsumed_by']:
      other = by_id.get(sid)
      if other and r['id'] in other['subsumed_by']:
        merged = groups.get(r['id'], {r['id']}) | groups.get(sid, {sid})
        for i in merged:
          groups[i] = merged
  kept_rule = {}
  for group in {frozenset(g) for g in groups.values()}:
    keep = min(group, key=lambda i: (not by_id[i]['in_app_files'], i))
    for i in group:
      kept_rule[i] = keep
      by_id[i]['subsumed_by'] = [
          s for s in by_id[i]['subsumed_by'] if s not in group
      ]
      by_id[i]['identical_to'] = [rules[j] for j in sorted(group) if j != i]
  identical_rules = [
      r for r in processed if kept_rule.get(r['id'], r['id']) != r['id']
  ]
  identical_ids = {r['id'] for r in identical_rules}

  candidates = [r for r in processed if r['id'] not in identical_ids]
  top_rules = [r for r in candidates if not r['subsumed_by']][:10]
  subsumed_rules = [r for r in candidates if r['subsumed_by']]

  for r in subsumed_rules + identical_rules:
    if r['subsumed_by']:
      r['subsumed_by_rules'] = [
          rules.get(sid, {'source': f'Rule#{sid}'}) for sid in r['subsumed_by']
      ]

  global_rules = [
      describe_rule(g, file_origins, maven_coordinates)
      for g in d.get('global_keep_rule_blast_radius_table', [])
  ]

  analysis_data = {
      'scores': {
          'optimization': f'{opt_score:.2f}%',
          'obfuscation': f'{obf_score:.2f}%',
          'shrinking': f'{shr_score:.2f}%',
      },
      'globals': global_rules,
      'top_impact_rules': top_rules,
      'subsumed_rules': subsumed_rules,
      'identical_rules': identical_rules,
  }

  os.makedirs(output_dir, exist_ok=True)
  with open(
      os.path.join(output_dir, 'analysis_result.txt'), 'w', encoding='utf-8'
  ) as f:
    f.write('\n'.join(result) + '\n\n' + json.dumps(analysis_data, indent=2))

  print(f"Analysis written to {os.path.join(output_dir, 'analysis_result.txt')}")


def main():
  """Entry point for CLI execution."""
  if len(sys.argv) > 1:
    target_path = sys.argv[1]
  else:
    candidates = [
        p
        for p in (
            'tmp/keepradius/keepruleradius.json',
            'tmp/r8analysis/keepruleradius.json',
        )
        if os.path.isfile(p)
    ]
    target_path = (
        max(candidates, key=os.path.getmtime)
        if candidates
        else 'tmp/keepradius/keepruleradius.json'
    )
  analyze(target_path)


if __name__ == '__main__':
  main()