#!/usr/bin/env python
#
# Copyright (C) 2025 The Android Open Source Project
#
# 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
#
#      http://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.
#
#
# Much of this implementation was borrowed from
# https://github.com/google/perfetto/blob/main/tools/install-build-deps
#

import hashlib
import os
import subprocess
import sys

ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PYTHON_REQUIREMENTS = os.path.join(ROOT_DIR, 'tools', 'requirements.txt')
PYTHON_VENV_DIR = os.path.join(ROOT_DIR, '.venv')
PYTHON_VENV_BIN_DIR = os.path.join(
    PYTHON_VENV_DIR, 'bin') if sys.platform != 'win32' else os.path.join(
        PYTHON_VENV_DIR, 'Scripts')
PYTHON_STATUS_FILE = os.path.join(PYTHON_VENV_DIR, '.last_install')

def file_hash(path):
  if not os.path.exists(path):
    return None
  with open(path, 'rb') as f:
    return hashlib.sha256(f.read()).hexdigest()

def is_venv_updated():
  """Returns True if the python venv is up-to-date."""
  if not os.path.exists(PYTHON_STATUS_FILE):
    return False
  with open(PYTHON_STATUS_FILE, 'r') as f:
    actual = f.read()
  expected = file_hash(PYTHON_REQUIREMENTS)
  return expected == actual

def create_venv():
  venv_pip = os.path.join(PYTHON_VENV_BIN_DIR, 'pip3')
  cur_python_interpreter = sys.executable
  if not os.path.exists(venv_pip):
    cmd = [cur_python_interpreter, '-m', 'venv', PYTHON_VENV_DIR]
    print(f'Installing python venv {" ".join(cmd)}')
    subprocess.check_call(cmd)

  cmd = [venv_pip, 'install', '-r', PYTHON_REQUIREMENTS]
  print(f'Updating python packages {" ".join(cmd)}')
  subprocess.check_call(cmd)
  with open(PYTHON_STATUS_FILE, 'w') as f:
    f.write(file_hash(PYTHON_REQUIREMENTS))

if __name__ == "__main__":
    if is_venv_updated():
        print("Torq virtual env is up-to-date")
        exit()
    create_venv()
    print("Torq virtual env updated")
