from pydantic import BaseModel, field_validator
from typing import Literal, NamedTuple
from TexSoup import TexNode
from enum import Enum


class SplitConfig(BaseModel):
    env: str
    on: Literal["next", "subtitle"]


class ConfigType(BaseModel):
    split: list[SplitConfig]

    @field_validator("split")
    @classmethod
    def ensure_unique_split(cls, v):
        envs = [x.env for x in v]
        if len(envs) != len(set(envs)):
            raise ValueError("Cannot have multiple environments set")
        return v


class Card(BaseModel):
    front: str
    back: str
    tag: str | None


class SectionConfig(BaseModel):
    name: str
    child: str | None


class ParsedEnv(NamedTuple):
    env: TexNode
    child: TexNode | None = None


def parse_section_config(configs: list[str] | None) -> list[SectionConfig] | None:
    if configs is None:
        return

    section_configs = []
    for config in configs:
        name, child, *_ = config.split(":") + [None]
        if name is not None:
            section_configs.append(SectionConfig(name=name, child=child))

    return section_configs


class DuplicateBehaviour(Enum):
    REPLACE = "replace"
    SKIP = "skip"
    CANCEL = "cancel"
