"""Model proxy and Recordset classes for Odoo data models.

Provides the Model class which allows dynamic access to all methods
proposed by an Odoo data model, and Recordset functionality for
browsing and manipulating records.

Originally from OdooRPC (LGPL-3.0), modernized for Python 3.10+.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

from odoorpc_toolbox import exceptions

if TYPE_CHECKING:
    from odoorpc_toolbox.environment import Environment

NORMALIZED_TYPES = (int, str, bytes)
FIELDS_RESERVED = ["id", "ids", "__odoo__", "__osv__", "__data__", "env"]


def _normalize_ids(ids) -> list[int]:
    """Normalize the ids argument for browse."""
    if not ids:
        return []
    if ids.__class__ in NORMALIZED_TYPES:
        return [ids]
    return list(ids)


class IncrementalRecords:
    """Helper class used internally by __iadd__ and __isub__ methods.

    Field descriptors adapt their behaviour when an instance of this class is set.
    """

    def __init__(self, tuples: list) -> None:
        self.tuples = tuples


class MetaModel(type):
    """Metaclass for Model. Defines class-level methods and RPC delegation."""

    _env: Environment | None = None

    def __getattr__(cls, method: str):
        """Provide dynamic access to a RPC method."""
        if method.startswith("_"):
            return super().__getattr__(method)

        def rpc_method(*args, **kwargs):
            if cls._odoo.config["auto_context"] and "context" not in kwargs:
                kwargs["context"] = cls.env.context
            return cls._odoo.execute_kw(cls._name, method, args, kwargs)

        return rpc_method

    def __repr__(cls) -> str:
        return f"Model({cls._name!r})"

    @property
    def env(cls) -> Environment:
        """The environment used for this model/recordset."""
        return cls._env


# Intermediate class to associate the MetaModel metaclass to Model
BaseModel = MetaModel("BaseModel", (), {})


class Model(BaseModel):
    """Base class for all data model proxies.

    All model proxies are generated by an Environment.

    Example:
        >>> User = odoo.env['res.users']
        >>> User
        Model('res.users')
        >>> user = User.browse(2)
        >>> user.name
        'Mitchell Admin'
    """

    __metaclass__ = MetaModel
    _odoo = None
    _name: str | None = None
    _columns: dict = {}

    def __init__(self) -> None:
        super().__init__()
        self._env_local: Environment | None = None
        self._from_record = None
        self._ids: list[int] = []
        self._values: dict[str, dict] = {}
        self._values_to_write: dict[str, dict] = {}
        for field in self._columns:
            self._values[field] = {}
            self._values_to_write[field] = {}
        self.with_context = self._with_context
        self.with_env = self._with_env

    @property
    def env(self) -> Environment:
        """The environment used for this model/recordset."""
        if self._env_local:
            return self._env_local
        return self.__class__._env

    @property
    def id(self) -> int | None:
        """ID of the record (or the first ID of a recordset)."""
        return self._ids[0] if self._ids else None

    @property
    def ids(self) -> list[int]:
        """IDs of the recordset."""
        return self._ids

    @classmethod
    def _browse(cls, env: Environment, ids, from_record=None, iterated=None) -> Model:
        """Create a recordset corresponding to ids attached to env.

        from_record: tuple (record, field) when the recordset is related to a parent record.
        iterated: an iterated recordset to share values with (no extra RPC queries).
        """
        records = cls()
        records._env_local = env
        records._ids = _normalize_ids(ids)
        if iterated:
            records._values = iterated._values
            records._values_to_write = iterated._values_to_write
        else:
            records._from_record = from_record
            records._values = {}
            records._values_to_write = {}
            for field in cls._columns:
                records._values[field] = {}
                records._values_to_write[field] = {}
            records._init_values()
        return records

    @classmethod
    def browse(cls, ids) -> Model:
        """Browse one or several records.

        Args:
            ids: A single ID or list of IDs.

        Returns:
            A Model instance (recordset).
        """
        return cls._browse(cls.env, ids)

    @classmethod
    def with_context(cls, *args, **kwargs) -> type[Model]:
        """Return a model attached to an environment with another context."""
        context = dict(args[0] if args else cls.env.context, **kwargs)
        return cls.with_env(cls.env(context=context))

    def _with_context(self, *args, **kwargs) -> Model:
        """Instance version of with_context."""
        context = dict(args[0] if args else self.env.context, **kwargs)
        return self.with_env(self.env(context=context))

    @classmethod
    def with_env(cls, env: Environment) -> type[Model]:
        """Return a model attached to env."""
        new_cls = type(cls.__name__, cls.__bases__, dict(cls.__dict__))
        new_cls._env = env
        return new_cls

    def _with_env(self, env: Environment) -> Model:
        """Instance version of with_env."""
        return self._browse(env, self._ids)

    def _init_values(self, context: dict | None = None) -> None:
        """Retrieve field values from the server."""
        if context is None:
            context = self.env.context
        basic_fields = []
        for field_name in self._columns:
            field = self._columns[field_name]
            if not getattr(field, "relation", False):
                basic_fields.append(field_name)
        if self.ids:
            rows = self.__class__.read(self.ids, basic_fields, context=context, load="_classic_write")
            ids_fetched = set()
            for row in rows:
                ids_fetched.add(row["id"])
                for field_name in row:
                    if field_name == "id":
                        continue
                    self._values[field_name][row["id"]] = row[field_name]
            ids_in_error = set(self.ids) - ids_fetched
            if ids_in_error:
                raise ValueError(f"There is no '{self._name}' record with IDs {list(ids_in_error)}.")
        else:
            default_get = self.__class__.default_get(list(self._columns), context=context)
            for field_name in self._columns:
                self._values[field_name][None] = default_get.get(field_name, False)

    def __getattr__(self, method: str):
        """Provide dynamic access to a RPC instance method (applied on current recordset)."""
        if method.startswith("_"):
            return super().__getattr__(method)

        def rpc_method(*args, **kwargs):
            args = tuple([self.ids]) + args
            if self._odoo.config["auto_context"] and "context" not in kwargs:
                kwargs["context"] = self.env.context
            return self._odoo.execute_kw(self._name, method, args, kwargs)

        return rpc_method

    def __getitem__(self, key):
        """If key is an integer or slice, return the corresponding record selection."""
        if isinstance(key, (int, slice)):
            return self._browse(self.env, self._ids[key], iterated=self)
        return getattr(self, key)

    def __int__(self) -> int:
        return self.id

    def __eq__(self, other) -> bool:
        return other.__class__ == self.__class__ and self.id == other.id

    __hash__ = BaseModel.__hash__

    def __ne__(self, other) -> bool:
        return other.__class__ != self.__class__ or self.id != other.id

    def __repr__(self) -> str:
        return f"Recordset({self._name!r}, {self.ids})"

    def __iter__(self):
        """Return an iterator over self."""
        for id_ in self._ids:
            yield self._browse(self.env, id_, iterated=self)

    def __bool__(self) -> bool:
        return bool(getattr(self, "_ids", True))

    def __len__(self) -> int:
        return len(self.ids)

    def __iadd__(self, records):
        if not self._from_record:
            raise exceptions.InternalError("No parent record to update")
        try:
            list(records)
        except TypeError:
            records = [records]
        parent = self._from_record[0]
        field = self._from_record[1]
        updated_values = parent._values_to_write[field.name]
        values = []
        if updated_values.get(parent.id):
            values = updated_values[parent.id][:]
        from odoorpc_toolbox.fields import records2ids

        for id_ in records2ids(records):
            if (3, id_) in values:
                values.remove((3, id_))
            if (4, id_) not in values:
                values.append((4, id_))
        return IncrementalRecords(values)

    def __isub__(self, records):
        if not self._from_record:
            raise exceptions.InternalError("No parent record to update")
        try:
            list(records)
        except TypeError:
            records = [records]
        parent = self._from_record[0]
        field = self._from_record[1]
        updated_values = parent._values_to_write[field.name]
        values = []
        if updated_values.get(parent.id):
            values = updated_values[parent.id][:]
        from odoorpc_toolbox.fields import records2ids

        for id_ in records2ids(records):
            if (4, id_) in values:
                values.remove((4, id_))
            if (3, id_) not in values:
                values.append((3, id_))
        return values
