# Copyright 2025 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit checks for Chromium-specific `gemini-cli` commands.

See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details on the presubmit API built into depot_tools.
"""

import tomllib

PRESUBMIT_VERSION = '2.0.0'
_CUSTOM_COMMANDS_DOC_URL = ('https://github.com/google-gemini/gemini-cli'
                             '/blob/main/docs/cli/commands.md#custom-commands')


def CheckCommands(input_api, output_api):
  cr_dir = input_api.os_path.join(input_api.PresubmitLocalPath(), 'cr')
  results = []

  for affected_file in input_api.AffectedTestableFiles(
        file_filter=lambda f: f.Extension() == '.toml'):
    if input_api.os_path.commonpath([affected_file.AbsoluteLocalPath(),
                                     cr_dir]) != cr_dir:
      error = output_api.PresubmitError(
          f'Move {affected_file.LocalPath()} under {cr_dir} to scope the '
          'command to `/cr:`.',
          long_text=_CUSTOM_COMMANDS_DOC_URL)
      results.append(error)

    contents = input_api.ReadFile(affected_file)
    try:
      definition = tomllib.loads(contents)
    except tomllib.TOMLDecodeError:
      error = output_api.PresubmitError(
          f'{affected_file.LocalPath()} is not valid TOML.',
          long_text=_CUSTOM_COMMANDS_DOC_URL)
      results.append(error)
      continue

    if not isinstance(definition.get('prompt'), str):
      error = output_api.PresubmitError(
          f'{affected_file.LocalPath()} must define a `prompt` key.',
          long_text=_CUSTOM_COMMANDS_DOC_URL)
      results.append(error)
    if not isinstance(definition.get('description'), str):
      warning = output_api.PresubmitPromptWarning(
          f'{affected_file.LocalPath()} should define a `description` key '
          'to replace the autogenerated placeholder.',
          long_text=_CUSTOM_COMMANDS_DOC_URL)
      results.append(warning)

  return results
