# coding=utf-8
# Copyright 2022 The Fiddle-Config 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
#
#     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.

"""Library for manipulating DAGs."""

import abc
import dataclasses
from typing import Any, List, Mapping, Tuple, Union


class PathElement(metaclass=abc.ABCMeta):
  """Element of a path."""

  @abc.abstractproperty
  def code(self) -> str:
    """Generates code for accessing this path."""
    raise NotImplementedError()


@dataclasses.dataclass(frozen=True)
class ListOrTupleItem(PathElement):
  """Index into a list or tuple."""
  base_obj: Union[List[Any], Tuple[Any, ...]]
  index: int

  @property
  def code(self) -> str:
    return f"[{self.index}]"


@dataclasses.dataclass(frozen=True)
class DictItem(PathElement):
  """An item from a dictionary with a given key."""
  base_obj: Mapping[Any, Any]
  key: Any

  @property
  def code(self) -> str:
    return f"[{self.key!r}]"


@dataclasses.dataclass(frozen=True)
class AttributeItem(PathElement):
  """An attribute of an object."""
  base_obj: Any
  name: str

  @property
  def code(self) -> str:
    return f".{self.name}"


class BuildableAttributeItem(AttributeItem):
  """An attribute of a Buildable."""


Path = List[PathElement]
