"""YAML configuration handling for the book."""

from __future__ import annotations

import base64
import mimetypes
from dataclasses import dataclass, field
from pathlib import Path

import yaml


@dataclass
class CoverConfig:
    """Cover configuration."""

    image: str | None = None
    title_color: str = "#ffffff"
    subtitle_color: str = "#cccccc"
    background_color: str = "#1a1a2e"


@dataclass
class ChapterConfig:
    """Chapter configuration."""

    file: str
    title: str | None = None


@dataclass
class PageConfig:
    """Page layout configuration."""

    size: str = "A5"
    margin_top: str = "20mm"
    margin_bottom: str = "25mm"
    margin_inner: str = "25mm"
    margin_outer: str = "20mm"


@dataclass
class FontConfig:
    """Font configuration."""

    body_family: str = "Georgia, 'Times New Roman', serif"
    body_size: str = "11pt"
    heading_family: str = "'Helvetica Neue', Arial, sans-serif"
    chapter_title_size: str = "28pt"
    line_height: str = "1.6"


@dataclass
class StyleConfig:
    """Visual style configuration."""

    page: PageConfig = field(default_factory=PageConfig)
    font: FontConfig = field(default_factory=FontConfig)
    drop_cap: bool = True
    chapter_break: str = "always"  # always | auto
    header_content: str = ""
    footer_content: str = ""


@dataclass
class OutputConfig:
    """Output configuration."""

    directory: str = "output"
    filename: str = "book"
    reader_filename: str = "index"
    print_filename: str = "print"
    open_browser: bool = True


@dataclass
class BookConfig:
    """Complete book configuration."""

    title: str = "Mi Libro"
    subtitle: str = ""
    author: str = "Autor"
    language: str = "es"
    description: str = ""
    publisher: str = ""
    year: str = ""
    isbn: str = ""
    dedication: str = ""
    epigraph: str = ""
    epigraph_author: str = ""
    cover: CoverConfig = field(default_factory=CoverConfig)
    chapters: list[ChapterConfig] = field(default_factory=list)
    style: StyleConfig = field(default_factory=StyleConfig)
    output: OutputConfig = field(default_factory=OutputConfig)


def load_config(config_path: Path) -> BookConfig:
    """Load book configuration from a YAML file."""
    with open(config_path, encoding="utf-8") as f:
        raw = yaml.safe_load(f)

    if raw is None:
        return BookConfig()

    book_data = raw.get("book", raw)

    # Cover
    cover_raw = book_data.get("cover", {})
    cover = CoverConfig(
        image=cover_raw.get("image"),
        title_color=cover_raw.get("title_color", "#ffffff"),
        subtitle_color=cover_raw.get("subtitle_color", "#cccccc"),
        background_color=cover_raw.get("background_color", "#1a1a2e"),
    )

    # Chapters
    chapters_raw = book_data.get("chapters", [])
    chapters = [
        ChapterConfig(
            file=ch["file"],
            title=ch.get("title"),
        )
        for ch in chapters_raw
    ]

    # Style
    style_raw = book_data.get("style", {})
    page_raw = style_raw.get("page", {})
    font_raw = style_raw.get("font", {})

    page = PageConfig(
        size=page_raw.get("size", "A5"),
        margin_top=page_raw.get("margin_top", "20mm"),
        margin_bottom=page_raw.get("margin_bottom", "25mm"),
        margin_inner=page_raw.get("margin_inner", "25mm"),
        margin_outer=page_raw.get("margin_outer", "20mm"),
    )

    font = FontConfig(
        body_family=font_raw.get("body_family", "Georgia, 'Times New Roman', serif"),
        body_size=font_raw.get("body_size", "11pt"),
        heading_family=font_raw.get(
            "heading_family", "'Helvetica Neue', Arial, sans-serif"
        ),
        chapter_title_size=font_raw.get("chapter_title_size", "28pt"),
        line_height=font_raw.get("line_height", "1.6"),
    )

    style = StyleConfig(
        page=page,
        font=font,
        drop_cap=style_raw.get("drop_cap", True),
        chapter_break=style_raw.get("chapter_break", "always"),
    )

    # Output
    output_raw = book_data.get("output", {})
    output = OutputConfig(
        directory=output_raw.get("directory", "output"),
        filename=output_raw.get("filename", "book"),
        reader_filename=output_raw.get("reader_filename", "index"),
        print_filename=output_raw.get("print_filename", "print"),
        open_browser=output_raw.get("open_browser", True),
    )

    return BookConfig(
        title=book_data.get("title", "Mi Libro"),
        subtitle=book_data.get("subtitle", ""),
        author=book_data.get("author", "Autor"),
        language=book_data.get("language", "es"),
        description=book_data.get("description", ""),
        publisher=book_data.get("publisher", ""),
        year=book_data.get("year", ""),
        isbn=book_data.get("isbn", ""),
        dedication=book_data.get("dedication", ""),
        epigraph=book_data.get("epigraph", ""),
        epigraph_author=book_data.get("epigraph_author", ""),
        cover=cover,
        chapters=chapters,
        style=style,
        output=output,
    )


def image_to_data_uri(image_path: Path) -> str:
    """Convert an image to a Data URI for embedding in HTML."""
    mime_type, _ = mimetypes.guess_type(str(image_path))
    if mime_type is None:
        mime_type = "image/jpeg"
    with open(image_path, "rb") as f:
        data = base64.b64encode(f.read()).decode("utf-8")
    return f"data:{mime_type};base64,{data}"
