# Copyright 2026 Google LLC
#
# 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.

"""Working directory helper tool to resolve path context issues."""

from __future__ import annotations

import os
from pathlib import Path
from typing import Any
from typing import Dict
from typing import List
from typing import Optional

from .path_normalizer import sanitize_generated_file_path


def resolve_file_path(
    file_path: str,
    session_state: Optional[Dict[str, Any]] = None,
    working_directory: Optional[str] = None,
) -> Path:
  """Resolve a file path using root directory from session state.

  This is a helper function that other tools can use to resolve file paths
  without needing to be async or return detailed resolution information.

  Args:
    file_path: File path (relative or absolute)
    session_state: Session state dict that may contain root_directory
    working_directory: Working directory to use as base (defaults to cwd)

  Returns:
    Resolved absolute Path object, guaranteed to be within the root directory.

  Raises:
    ValueError: If ``file_path`` resolves outside the root directory, e.g. via
      ``..`` traversal or an absolute path pointing outside the root.
  """
  normalized_path = sanitize_generated_file_path(file_path)
  file_path_obj = Path(normalized_path)

  # Get root directory from session state, default to "./"
  root_directory = "./"
  if session_state and "root_directory" in session_state:
    root_directory = session_state["root_directory"]

  root_path_obj = Path(root_directory)
  if root_path_obj.is_absolute():
    resolved_root = root_path_obj
  elif working_directory:
    resolved_root = Path(working_directory) / root_directory
  else:
    resolved_root = Path(os.getcwd()) / root_directory
  resolved_root = resolved_root.resolve()

  if file_path_obj.is_absolute():
    candidate = file_path_obj.resolve()
  else:
    candidate = (resolved_root / file_path_obj).resolve()

  # Keep the resolved path within the root to block path-traversal escapes.
  try:
    candidate.relative_to(resolved_root)
  except ValueError as exc:
    raise ValueError(
        f"File path {file_path!r} resolves outside the root directory"
        f" {resolved_root}."
    ) from exc
  return candidate


def resolve_file_paths(
    file_paths: List[str],
    session_state: Optional[Dict[str, Any]] = None,
    working_directory: Optional[str] = None,
) -> List[Path]:
  """Resolve multiple file paths using root directory from session state.

  Args:
    file_paths: List of file paths (relative or absolute)
    session_state: Session state dict that may contain root_directory
    working_directory: Working directory to use as base (defaults to cwd)

  Returns:
    List of resolved absolute Path objects
  """
  return [
      resolve_file_path(path, session_state, working_directory)
      for path in file_paths
  ]
