"""Document generation utilities for D.intelligence branded outputs."""

from __future__ import annotations

import datetime
from pathlib import Path

from docx import Document
from docx.shared import Inches, Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH

from dintel.brand import (
    BRAND_NAME,
    COLOR_PRIMARY,
    COLOR_SECONDARY,
    COLOR_TEXT,
    FONT_FALLBACK_EN,
    FONT_FALLBACK_KR,
    TAGLINE,
)


def create_branded_doc(
    title: str,
    subtitle: str = "",
    author: str = "D.intelligence",
) -> Document:
    """Create a new DOCX document with D.intelligence branding."""
    doc = Document()

    # Core properties
    doc.core_properties.author = author
    doc.core_properties.title = title
    doc.core_properties.created = datetime.datetime.now()

    # Default style
    style = doc.styles["Normal"]
    font = style.font
    font.name = FONT_FALLBACK_EN
    font.size = Pt(10)
    font.color.rgb = RGBColor(*COLOR_TEXT)

    # Title
    heading = doc.add_heading(title, level=0)
    for run in heading.runs:
        run.font.color.rgb = RGBColor(*COLOR_PRIMARY)

    if subtitle:
        p = doc.add_paragraph(subtitle)
        p.alignment = WD_ALIGN_PARAGRAPH.CENTER
        for run in p.runs:
            run.font.color.rgb = RGBColor(*COLOR_SECONDARY)
            run.font.size = Pt(12)

    # Tagline footer
    p = doc.add_paragraph(f"{BRAND_NAME} — {TAGLINE}")
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    for run in p.runs:
        run.font.size = Pt(8)
        run.font.color.rgb = RGBColor(*COLOR_SECONDARY)

    doc.add_paragraph("")  # spacer
    return doc


def add_section_heading(doc: Document, text: str, level: int = 1) -> None:
    """Add a branded section heading."""
    heading = doc.add_heading(text, level=level)
    for run in heading.runs:
        run.font.color.rgb = RGBColor(*COLOR_PRIMARY)


def add_bilingual_heading(
    doc: Document, en_text: str, kr_text: str, level: int = 2
) -> None:
    """Add a bilingual heading (English + Korean subtitle)."""
    heading = doc.add_heading(en_text, level=level)
    for run in heading.runs:
        run.font.color.rgb = RGBColor(*COLOR_PRIMARY)
    p = doc.add_paragraph(kr_text)
    for run in p.runs:
        run.font.color.rgb = RGBColor(*COLOR_SECONDARY)
        run.font.size = Pt(10)


def save_doc(doc: Document, output_path: str | Path) -> Path:
    """Save document and return the path."""
    output_path = Path(output_path)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    doc.save(str(output_path))
    return output_path
