"""Form definitions — bundled JSON form specs.

Each form has sections → fields with type, validation, help text, required flag.
"""

from __future__ import annotations

import json
from dataclasses import dataclass, field as dc_field
from typing import Any

# ---------------------------------------------------------------------------
# Data classes
# ---------------------------------------------------------------------------


@dataclass
class FormField:
    id: str
    label: str
    type: str  # string, choice, integer, percentage
    required: bool = True
    default: Any = None
    options: list[str] | None = None
    validation: str = ""
    help: str = ""
    prefilled: bool = False  # If True, show but don't prompt (user can override)
    faq_keywords: list[str] = dc_field(default_factory=list)


@dataclass
class FormSection:
    id: str
    title: str
    fields: list[FormField]


@dataclass
class FormDefinition:
    form_id: str
    version: str
    title: str
    description: str
    sections: list[FormSection]


# ---------------------------------------------------------------------------
# Bundled definitions
# ---------------------------------------------------------------------------

ENTITY_FORMATION = FormDefinition(
    form_id="entity-formation",
    version="1.0.0",
    title="Form a Wyoming DAO LLC",
    description="Create a real Wyoming LAO (Limited Autonomous Organization) LLC with on-chain governance.",
    sections=[
        FormSection(
            id="basics",
            title="Entity Basics",
            fields=[
                FormField(
                    id="entity_name",
                    label="What do you want to name your LLC?",
                    type="string",
                    required=True,
                    validation=r"Must end in 'LAO LLC' or 'LAO L.L.C.'",
                    help="Wyoming requires a legal suffix. Corpo uses LAO (Limited Autonomous Organization) to signal compliance.",
                    faq_keywords=["name", "lao"],
                ),
                FormField(
                    id="entity_type",
                    label="Entity type",
                    type="choice",
                    options=["dao_llc"],
                    default="dao_llc",
                    help="Currently only DAO LLC formation is supported.",
                    faq_keywords=["entity"],
                ),
            ],
        ),
        FormSection(
            id="agents",
            title="Registered Agent & Management",
            fields=[
                FormField(
                    id="registered_agent",
                    label="Registered agent",
                    type="string",
                    default="Wyoming Agents (wyomingagents.com)",
                    prefilled=True,
                    help="Wyoming requires a registered agent in-state. Corpo partners with Wyoming Agents.",
                    faq_keywords=["registered agent"],
                ),
                FormField(
                    id="management_type",
                    label="Management type",
                    type="string",
                    default="algorithmically managed",
                    prefilled=True,
                    help="DAO LLCs in Wyoming are algorithmically managed via smart contract governance.",
                    faq_keywords=["smart contract"],
                ),
            ],
        ),
        FormSection(
            id="governance",
            title="Governance Configuration",
            fields=[
                FormField(
                    id="governance_platform",
                    label="Governance platform",
                    type="choice",
                    options=["solana"],
                    default="solana",
                    help="The platform for on-chain governance. Currently uses Solana Realms (spl-governance).",
                    faq_keywords=["solana", "realms"],
                ),
                FormField(
                    id="initial_token_supply",
                    label="Initial governance token supply",
                    type="integer",
                    required=True,
                    default=1000000,
                    help="Number of governance tokens to mint. Each token = 1 vote.",
                    faq_keywords=["token", "vote"],
                ),
                FormField(
                    id="voting_threshold",
                    label="Voting threshold (%)",
                    type="percentage",
                    required=True,
                    default=50,
                    help="Percentage of deposited tokens needed to pass a proposal. Default: 50%.",
                    faq_keywords=["vote", "quorum"],
                ),
            ],
        ),
        FormSection(
            id="donation",
            title="Support Corpo",
            fields=[
                FormField(
                    id="donation_percentage",
                    label="Governance token donation (%)",
                    type="percentage",
                    required=False,
                    default=0,
                    help=(
                        "Corpo, LLC is devoted to bringing AI agents real-world agency "
                        "— allowing them to own corporations, real estate, and investments, "
                        "and to engage in actions like lobbying. Donating a small percentage "
                        "of your governance tokens helps fund this work. Enter 0 to skip."
                    ),
                    faq_keywords=[],
                ),
            ],
        ),
    ],
)

_REGISTRY: dict[str, FormDefinition] = {
    "entity-formation": ENTITY_FORMATION,
}


def get_form_definition(form_id: str) -> FormDefinition | None:
    """Get a form definition by ID."""
    return _REGISTRY.get(form_id)


def list_form_types() -> list[str]:
    """List available form type IDs."""
    return list(_REGISTRY.keys())


def form_definition_to_dict(form: FormDefinition) -> dict:
    """Serialize a FormDefinition to a plain dict (for JSON output)."""
    return {
        "form_id": form.form_id,
        "version": form.version,
        "title": form.title,
        "description": form.description,
        "sections": [
            {
                "id": s.id,
                "title": s.title,
                "fields": [
                    {
                        k: v
                        for k, v in {
                            "id": f.id,
                            "label": f.label,
                            "type": f.type,
                            "required": f.required,
                            "default": f.default,
                            "options": f.options,
                            "validation": f.validation or None,
                            "help": f.help or None,
                            "prefilled": f.prefilled or None,
                        }.items()
                        if v is not None
                    }
                    for f in s.fields
                ],
            }
            for s in form.sections
        ],
    }
