#!/usr/bin/env python3
# Copyright (C) 2021 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.

import argparse
import os
import sys

UI_DIR = os.path.dirname(__file__)


def main():
  parser = argparse.ArgumentParser()
  parser.add_argument(
      '--interactive',
      '-i',
      action='store_true',
      help='Run in interactive mode')
  parser.add_argument(
      '--rebaseline', '-r', action='store_true', help='Rebaseline screenshots')
  parser.add_argument('--out', help='out directory')
  parser.add_argument('--no-build', action='store_true')
  parser.add_argument('--no-depscheck', action='store_true')
  parser.add_argument('--workers', help='Number of playwright workers to use')
  parser.add_argument('filters', nargs='*')
  args = parser.parse_args()

  cmd = ['./pnpm', 'exec', 'playwright', 'test']
  if args.interactive:
    if args.rebaseline:
      print('--interactive and --rebaseline are mutually exclusive')
      return 1
    cmd += ['--ui']
  elif args.rebaseline:
    cmd += ['--update-snapshots']

  if args.workers:
    cmd += ['--workers', args.workers]

  cmd += args.filters

  env = dict(os.environ.items())
  dev_server_args = []
  if args.out:
    out_rel_path = os.path.relpath(args.out, UI_DIR)
    env['OUT_DIR'] = out_rel_path
    dev_server_args += ['--out', out_rel_path]
  if args.no_build:
    dev_server_args += ['--no-build']
  if args.no_depscheck:
    dev_server_args += ['--no-depscheck']
  env['DEV_SERVER_ARGS'] = ' '.join(dev_server_args)
  os.chdir(UI_DIR)
  os.execve(cmd[0], cmd, env)


if __name__ == '__main__':
  sys.exit(main())
