"""Structural patterns: how objects are composed."""
from __future__ import annotations

import functools
import time
from abc import ABC, abstractmethod
from typing import Callable, Dict, List


# Adapter: make an existing interface fit the one your code expects.
class LegacyPaymentGateway:
    def make_payment(self, amount_cents: int, card: str) -> dict:
        return {"ok": True, "charged": amount_cents, "card_last4": card[-4:]}


class PaymentProcessor(ABC):
    @abstractmethod
    def pay(self, amount: float, card: str) -> bool: ...


class LegacyGatewayAdapter(PaymentProcessor):
    def __init__(self, gateway: LegacyPaymentGateway):
        self.gateway = gateway

    def pay(self, amount: float, card: str) -> bool:
        return self.gateway.make_payment(round(amount * 100), card)["ok"]


# Decorator: add behaviour around an object without changing it (object form) ...
class DataSource(ABC):
    @abstractmethod
    def write(self, data: str) -> str: ...


class FileSource(DataSource):
    def write(self, data: str) -> str:
        return data


class SourceDecorator(DataSource):
    def __init__(self, wrapped: DataSource):
        self.wrapped = wrapped


class UppercaseDecorator(SourceDecorator):
    def write(self, data: str) -> str:
        return self.wrapped.write(data.upper())


class ReverseDecorator(SourceDecorator):
    def write(self, data: str) -> str:
        return self.wrapped.write(data[::-1])


# ... and Python's function decorators are the same idea for functions.
def retry(times: int, exceptions=(Exception,), delay: float = 0.0):
    def wrap(fn: Callable):
        @functools.wraps(fn)
        def inner(*args, **kwargs):
            for attempt in range(times):
                try:
                    return fn(*args, **kwargs)
                except exceptions:
                    if attempt == times - 1:
                        raise
                    time.sleep(delay)
        return inner
    return wrap


# Facade: one simple entry point over a complicated subsystem.
class Inventory:
    def __init__(self):
        self.stock = {"book": 2}

    def reserve(self, item: str) -> bool:
        if self.stock.get(item, 0) > 0:
            self.stock[item] -= 1
            return True
        return False


class Billing:
    def charge(self, user: str, item: str) -> str:
        return f"charged {user} for {item}"


class Shipping:
    def ship(self, user: str, item: str) -> str:
        return f"shipped {item} to {user}"


class OrderFacade:
    def __init__(self):
        self.inventory, self.billing, self.shipping = Inventory(), Billing(), Shipping()

    def place_order(self, user: str, item: str) -> List[str]:
        if not self.inventory.reserve(item):
            return ["out of stock"]
        return [self.billing.charge(user, item), self.shipping.ship(user, item)]


# Proxy: same interface, controls access (caching, auth, lazy loading).
class WeatherService(ABC):
    @abstractmethod
    def forecast(self, city: str) -> str: ...


class RemoteWeather(WeatherService):
    def __init__(self):
        self.calls = 0

    def forecast(self, city: str) -> str:
        self.calls += 1
        return f"sunny in {city}"


class CachingWeatherProxy(WeatherService):
    def __init__(self, real: WeatherService):
        self.real, self.cache = real, {}

    def forecast(self, city: str) -> str:
        if city not in self.cache:
            self.cache[city] = self.real.forecast(city)
        return self.cache[city]


# Composite: treat single objects and groups the same way.
class FileSystemNode(ABC):
    def __init__(self, name: str):
        self.name = name

    @abstractmethod
    def size(self) -> int: ...


class File(FileSystemNode):
    def __init__(self, name: str, size: int):
        super().__init__(name)
        self._size = size

    def size(self) -> int:
        return self._size


class Folder(FileSystemNode):
    def __init__(self, name: str):
        super().__init__(name)
        self.children: Dict[str, FileSystemNode] = {}

    def add(self, node: FileSystemNode) -> "Folder":
        self.children[node.name] = node
        return self

    def size(self) -> int:
        return sum(child.size() for child in self.children.values())
