# retoor <retoor@molodetz.nl>

from typing import Any, Union, get_args, get_origin

from pydantic import BaseModel

_PLACEHOLDERS = {
    "uid": "UID",
    "username": "username",
    "slug": "slug",
    "url": "/path",
    "email": "user@example.com",
    "title": "Title",
    "content": "text",
    "description": "text",
    "bio": "text",
    "language": "python",
    "topic": "random",
    "status": "published",
    "next_cursor": "2026-01-01T00:00:00+00:00",
    "created_at": "2026-01-01T00:00:00+00:00",
    "updated_at": "2026-01-01T00:00:00+00:00",
    "synced_at": "2026-01-01T00:00:00+00:00",
    "time_ago": "2 hours ago",
}


def _placeholder(name: str) -> str:
    for token, value in _PLACEHOLDERS.items():
        if token in name:
            return value
    return "string"


def _unwrap_optional(annotation):
    if get_origin(annotation) is Union:
        args = [arg for arg in get_args(annotation) if arg is not type(None)]
        return args[0] if args else Any
    return annotation


def _value(name, annotation, stack):
    annotation = _unwrap_optional(annotation)
    origin = get_origin(annotation)
    if origin in (list, set, tuple):
        args = get_args(annotation)
        inner = args[0] if args else str
        if isinstance(inner, type) and issubclass(inner, BaseModel) and inner in stack:
            return []
        return [_value(name, inner, stack)]
    if origin is dict or annotation is dict:
        return {}
    if annotation in (list, set, tuple):
        return []
    if isinstance(annotation, type) and issubclass(annotation, BaseModel):
        return _from_model(annotation, stack)
    if annotation is bool:
        return False
    if annotation is int:
        return 0
    if annotation is float:
        return 0.0
    if annotation is Any:
        return None
    return _placeholder(name)


def _from_model(model, stack):
    if model in stack:
        return {}
    stack = stack | {model}
    example = {}
    for name, info in model.model_fields.items():
        example[name] = _value(name, info.annotation, stack)
    return example


def schema_example(model):
    return _from_model(model, frozenset())


def action_example(redirect, data=None):
    return {"ok": True, "redirect": redirect, "data": data}
