# Copyright 2020 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import base64
import gzip
import json
import os
import re

from absl.testing import absltest

import jax
from jax import jit, make_jaxpr, numpy as jnp
from jax import lax
from jax._src import config
from jax._src import jaxpr_util
from jax._src import test_util as jtu
from jax._src.lib import _jax


config.parse_flags_with_absl()


class JaxprStatsTest(jtu.JaxTestCase):

  def test_primitives(self):
    def f(x, y):
      s = jit(jnp.sin)(x)
      return jnp.sin(s) + jnp.cos(y)

    hist = jaxpr_util.primitives(make_jaxpr(f)(1., 1.))

    primitives = ['add', 'sin', 'cos', 'jit']
    for k in primitives:
      assert k in hist, k
    self.assertEqual(hist['sin'], 2)
    self.assertTrue(all(count == 1 for k, count in hist.items() if k != 'sin'))

  def test_primitives_by_source(self):
    def f(x, y):
      s = jnp.sin(x)
      return jnp.sin(s) + jnp.cos(y)

    hist = jaxpr_util.primitives_by_source(make_jaxpr(f)(1., 1.))

    sin_keys = [k for k in hist.keys() if k.startswith('sin @ ')]
    rem_keys = [k for k in hist.keys() if not k.startswith('sin @ ')]

    self.assertEqual(sum(hist[k] for k in sin_keys), 2)
    self.assertTrue(all(hist[k] == 1 for k in rem_keys))

  def test_primitives_by_shape(self):
    def f(x, y):
      def sub(x, y):
        return jnp.sum(jnp.array([x, y]))
      s = jit(sub)(x, y)
      return jnp.sin(s) + jnp.cos(y)

    hist = jaxpr_util.primitives_by_shape(make_jaxpr(f)(1., 1.))

    t = '64' if config.enable_x64.value else '32'
    shapes = [
        f'add :: float{t}[]',
        f'sin :: float{t}[]',
        f'cos :: float{t}[]',
        f'reduce_sum :: float{t}[]',
        f'concatenate :: float{t}[2]',
        f'jit :: float{t}[]',
    ]
    for k in shapes:
      self.assertEqual(hist[k], 1)

  def test_source_locations(self):
    def f(x, y):
      s = jnp.sin(x)                  # sin
      return jnp.sin(s) + jnp.cos(y)  # sin, cos, add

    hist = jaxpr_util.source_locations(make_jaxpr(f)(1., 1.))
    self.assertEqual(sum(hist.values()), 4)

  def test_source_locations_exclude_contextlib(self):

    def f(x):
      # This generates a stack where the most recent non-jax frame
      # comes from contextlib.
      return jax.named_call(jnp.cos, name='test')(x)

    hist = jaxpr_util.source_locations(make_jaxpr(f)(jnp.arange(8.)))
    for filename in hist.keys():
      self.assertIn(os.path.basename(__file__), filename)

  def test_pprof_equation_profile(self):
    def f(x, y):
      s = jit(jnp.sin)(x)
      return jnp.sin(s) + jnp.cos(y)
    profile_gz = jaxpr_util.pprof_equation_profile(make_jaxpr(f)(1., 1.))
    profile_proto = gzip.decompress(profile_gz)
    json_str = _jax.pprof_profile_to_json(profile_proto)
    profile = json.loads(json_str)
    self.assertSetEqual(
        {'sampleType', 'sample', 'stringTable', 'location', 'function', 'comment'},
        set(profile.keys()))

  def test_all_eqns_with_traceback(self):
    @jit
    def g(x):
      return jax.lax.sin(x)

    def f(x):
      return g(x) + 1.

    jaxpr = make_jaxpr(f)(1.)

    eqns = list(jaxpr_util._all_eqns_with_traceback(jaxpr, None, set()))

    self.assertGreater(len(eqns), 1)

    jit_tb = None
    sin_tb = None

    for tb, eqn in eqns:
      if eqn.primitive.name == 'jit':
        jit_tb = tb
      elif eqn.primitive.name == 'sin':
        sin_tb = tb

    self.assertIsNotNone(jit_tb)
    self.assertIsNotNone(sin_tb)

    jit_frames = jit_tb.raw_frames()[0]
    sin_frames = sin_tb.raw_frames()[0]

    self.assertGreater(len(sin_frames), len(jit_frames))
    self.assertEqual(sin_frames[-len(jit_frames):], jit_frames)


  def test_count_eqns(self):
    # Test a simple flat jaxpr
    def f(x):
      return x + 2
    jaxpr = make_jaxpr(f)(42)
    # Check that accessing the property works on the ClosedJaxpr
    self.assertEqual(jaxpr_util.count_eqns(jaxpr), 1)

    # Test a higher-order jaxpr (contains nested subjaxprs)
    def g(x):
      return lax.cond(x > 0, lambda x: x + 2, lambda x: x - 2, x)
    jaxpr_nested = make_jaxpr(g)(42)

    # Verify the property resolves successfully and aggregates the nested equations
    # (should be > 1 due to the condition and branch eqns)
    self.assertEqual(jaxpr_util.count_eqns(jaxpr_nested), 5)

  def test_jaxpr_to_html(self):
    def f(x):
      return x + 2
    jaxpr = make_jaxpr(f)(42)

    html_content = jaxpr_util.jaxpr_to_html(jaxpr)

    self.assertIsInstance(html_content, str)
    self.assertIn("<!DOCTYPE html>", html_content)
    self.assertIn('<div id="jaxpr-container">', html_content)

    # Extract base64 data
    match = re.search(r'const base64Data = "([^"]+)";', html_content)
    self.assertIsNotNone(match)
    base64_data = match.group(1)

    # Decode and decompress
    compressed = base64.b64decode(base64_data)
    decompressed = gzip.decompress(compressed).decode("utf-8")
    data = json.loads(decompressed)

    self.assertIn("lines", data)
    self.assertIn("frames", data)
    self.assertIn("dag", data)
    self.assertIn("strings", data)
    self.assertIn("string_to_lines", data)

    string_to_lines = data["string_to_lines"]
    self.assertIsInstance(string_to_lines, dict)
    for k, v in string_to_lines.items():
      self.assertTrue(k.isdigit())
      self.assertIsInstance(v, list)
      self.assertTrue(all(isinstance(i, int) for i in v))


    # Verify that the pretty printed jaxpr lines are present
    lines = data["lines"]
    self.assertTrue(any("add" in line for line in lines))


if __name__ == "__main__":
  absltest.main(testLoader=jtu.JaxTestLoader())
