from typing import Literal, Optional, Dict, Any

from dataclasses import dataclass

LegendStyle = Literal["compact_bottom", "right", "top", "inside_top_right", "none"]


@dataclass(frozen=True)
class LegendSpec:
    style: LegendStyle = "compact_bottom"
    font_size: int = 12
    bgcolor: str = "rgba(0,0,0,0)"
    borderwidth: int = 0
    itemwidth: Optional[int] = None
    tracegroupgap: Optional[int] = None

    def build(self) -> Dict[str, Any]:
        if self.style == "none":
            return {"showlegend": False}

        base = dict(
            bgcolor=self.bgcolor,
            borderwidth=self.borderwidth,
            font=dict(size=self.font_size),
        )

        if self.style == "compact_bottom":
            base.update(
                orientation="h",
                yanchor="bottom",
                y=-0.20,
                xanchor="left",
                x=0,
            )
        elif self.style == "top":
            base.update(
                orientation="h",
                yanchor="bottom",
                y=1.02,
                xanchor="left",
                x=0,
            )
        elif self.style == "right":
            base.update(
                orientation="v",
                yanchor="top",
                y=1,
                xanchor="left",
                x=1.02,
            )
        elif self.style == "inside_top_right":
            base.update(
                orientation="v",
                yanchor="top",
                y=0.98,
                xanchor="right",
                x=0.98,
                bgcolor="rgba(255,255,255,0.6)",
            )

        if self.itemwidth is not None:
            base["itemwidth"] = self.itemwidth
        if self.tracegroupgap is not None:
            base["tracegroupgap"] = self.tracegroupgap

        return {"showlegend": True, "legend": base}