"""Creational patterns: how objects get created."""
from __future__ import annotations

import copy
import threading
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Dict, List, Optional


# Singleton: one shared instance. In Python a module-level object is usually simpler;
# this thread-safe version shows the classic shape.
class Config:
    _instance: Optional["Config"] = None
    _lock = threading.Lock()

    def __new__(cls) -> "Config":
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = super().__new__(cls)
                    cls._instance.values = {}
        return cls._instance


# Factory method: subclasses (or a registry) decide which concrete class to create.
class Notifier(ABC):
    @abstractmethod
    def send(self, to: str, message: str) -> str: ...


class EmailNotifier(Notifier):
    def send(self, to: str, message: str) -> str:
        return f"email to {to}: {message}"


class SmsNotifier(Notifier):
    def send(self, to: str, message: str) -> str:
        return f"sms to {to}: {message}"


_NOTIFIERS = {"email": EmailNotifier, "sms": SmsNotifier}


def create_notifier(channel: str) -> Notifier:
    try:
        return _NOTIFIERS[channel]()
    except KeyError:
        raise ValueError(f"unknown channel: {channel}") from None


# Abstract factory: a family of related objects that must match each other.
class Button(ABC):
    @abstractmethod
    def render(self) -> str: ...


class Checkbox(ABC):
    @abstractmethod
    def render(self) -> str: ...


class UIFactory(ABC):
    @abstractmethod
    def button(self) -> Button: ...

    @abstractmethod
    def checkbox(self) -> Checkbox: ...


class DarkButton(Button):
    def render(self) -> str:
        return "[dark button]"


class DarkCheckbox(Checkbox):
    def render(self) -> str:
        return "[dark checkbox]"


class LightButton(Button):
    def render(self) -> str:
        return "[light button]"


class LightCheckbox(Checkbox):
    def render(self) -> str:
        return "[light checkbox]"


class DarkTheme(UIFactory):
    def button(self) -> Button:
        return DarkButton()

    def checkbox(self) -> Checkbox:
        return DarkCheckbox()


class LightTheme(UIFactory):
    def button(self) -> Button:
        return LightButton()

    def checkbox(self) -> Checkbox:
        return LightCheckbox()


# Builder: construct a complex object step by step, validating at the end.
@dataclass(frozen=True)
class HttpRequest:
    method: str
    url: str
    headers: Dict[str, str]
    body: Optional[str]


class HttpRequestBuilder:
    def __init__(self, url: str):
        self._url, self._method, self._headers, self._body = url, "GET", {}, None

    def method(self, method: str) -> "HttpRequestBuilder":
        self._method = method.upper()
        return self

    def header(self, key: str, value: str) -> "HttpRequestBuilder":
        self._headers[key] = value
        return self

    def json(self, body: str) -> "HttpRequestBuilder":
        self._body = body
        return self.header("Content-Type", "application/json")

    def build(self) -> HttpRequest:
        if self._body is not None and self._method in ("GET", "HEAD"):
            raise ValueError(f"{self._method} requests cannot have a body")
        return HttpRequest(self._method, self._url, dict(self._headers), self._body)


# Prototype: clone a configured object instead of building it from scratch.
@dataclass
class Document:
    title: str
    tags: List[str] = field(default_factory=list)

    def clone(self) -> "Document":
        return copy.deepcopy(self)
