"""Template config generation helpers used by `pptx init-config`."""

from __future__ import annotations

from pathlib import Path

from pptx import Presentation

from .inspect_pptx import resolve_theme_colors


def build_init_config_output(template_path: str) -> str:
    """Generate starter template-config YAML by introspecting a PPTX template."""
    prs = Presentation(template_path)
    theme_colors = resolve_theme_colors(prs)

    # --- Slide dimensions ---
    slide_w = int(prs.slide_width or 12192000)
    slide_h = int(prs.slide_height or 6858000)

    # --- Theme fonts ---
    headline_font = "Calibri"
    body_font = "Calibri"
    try:
        from lxml import etree as _etree

        ns = "http://schemas.openxmlformats.org/drawingml/2006/main"
        master_part = prs.slide_masters[0].part
        for rel in master_part.rels.values():
            if "theme" in str(rel.reltype):
                theme_el: _etree._Element = rel.target_part.element  # type: ignore[union-attr]
                major_el: _etree._Element | None = theme_el.find(  # type: ignore[assignment]
                    f".//{{{ns}}}majorFont/{{{ns}}}latin"
                )
                minor_el: _etree._Element | None = theme_el.find(  # type: ignore[assignment]
                    f".//{{{ns}}}minorFont/{{{ns}}}latin"
                )
                if major_el is not None:
                    tf = str(major_el.get("typeface") or "")  # type: ignore[arg-type]
                    if tf:
                        headline_font = tf
                if minor_el is not None:
                    tf = str(minor_el.get("typeface") or "")  # type: ignore[arg-type]
                    if tf:
                        body_font = tf
                break
    except Exception:
        pass

    # --- Placeholders from first content layout ---
    placeholder_map: dict[str, int] = {"title": 0, "subtitle": 1}
    layout_names: list[str] = []
    for layout in prs.slide_layouts:
        if layout.name:
            layout_names.append(layout.name)

    # Scan all layouts for placeholder indices
    for layout in prs.slide_layouts:
        for ph in layout.placeholders:
            name_lower = ph.name.lower()
            idx = ph.placeholder_format.idx
            if "tracker" in name_lower or "on-page" in name_lower or "breadcrumb" in name_lower:
                placeholder_map["tracker"] = idx
            elif "source" in name_lower or "footnote" in name_lower:
                placeholder_map.setdefault("source", idx)

    # --- Estimate layout geometry from first content layout ---
    # Find a "Default" or first non-title layout
    content_layout = None
    for layout in prs.slide_layouts:
        if layout.name and "default" in layout.name.lower():
            content_layout = layout
            break
    if content_layout is None and len(prs.slide_layouts) > 1:
        content_layout = prs.slide_layouts[1]

    # Estimate margins and key Y positions from placeholder positions
    left_margin = 554736
    right_margin = 554736
    title_y = 182372
    content_start_y = 1710000
    footer_y = int(slide_h * 0.94)
    header_line_y = 1181907

    if content_layout is not None:
        for ph in content_layout.placeholders:
            idx = ph.placeholder_format.idx
            if idx == 0:  # title
                title_y = int(ph.top)
                left_margin = int(ph.left)
                right_margin = slide_w - int(ph.left) - int(ph.width)
            elif int(ph.top) > slide_h * 0.5:
                # Below midpoint — likely footer area
                footer_y = int(ph.top)
            elif int(ph.top) > content_start_y * 0.8:
                content_start_y = int(ph.top)

        # Header line is typically just below subtitle
        for ph in content_layout.placeholders:
            idx = ph.placeholder_format.idx
            if idx == 1:  # subtitle
                header_line_y = int(ph.top) + int(ph.height) + 10000
                break

    # --- Map theme colors to semantic names ---
    def _theme_hex(name: str, fallback: str) -> str:
        val = theme_colors.get(name, fallback)
        return f"#{val}" if not val.startswith("#") else val

    dk1 = _theme_hex("dk1", "000000")
    lt1 = _theme_hex("lt1", "FFFFFF")
    dk2 = _theme_hex("dk2", "444444")
    lt2 = _theme_hex("lt2", "F0F0F0")
    accent1 = _theme_hex("accent1", "4472C4")
    accent3 = _theme_hex("accent3", "A5A5A5")

    # --- Build config ---
    config_lines = [
        f"# Template config generated from: {Path(template_path).name}",
        "# Generated by: pptx init-config",
        "# Review and adjust values — especially bullets, spacing, and colors.",
        "",
        "colors:",
        f'  midnight: "{dk1}"          # dk1 / primary text',
        f'  light_1: "{lt1}"           # lt1 / primary background',
        f'  light_2: "{lt2}"           # lt2 / secondary background',
        f'  slate: "{dk2}"             # dk2 / secondary text',
        f'  electric_blue: "{accent1}" # accent1 / primary accent',
        f'  cyan: "{accent3}"          # accent3 / secondary accent',
        '  red: "#E5546C"             # RAG: critical (adjust to your palette)',
        '  orange: "#FAA082"          # RAG: high',
        '  beige: "#E8BDAD"           # RAG: neutral',
        '  light_green: "#92D050"     # RAG: medium',
        '  green: "#00B050"           # RAG: low',
        "",
        "fonts:",
        f'  headline: "{headline_font}"',
        f'  body: "{body_font}"',
        "",
        "font_sizes:",
        "  title: 24",
        "  subtitle: 16",
        "  table_header: 14",
        "  table_body: 12",
        "  footnote: 8",
        "  tracker: 8",
        "  default: 12",
        "",
        "# Soft limits used for agent-friendly warnings",
        "text_limits:",
        "  title_max_lines: 2",
        "  subtitle_max_lines: 1",
        "  title_slide_subtitle_max_lines: 1",
        "",
        "layout:",
        f"  slide_width_emu: {slide_w}",
        f"  slide_height_emu: {slide_h}",
        f"  left_margin_emu: {left_margin}",
        f"  right_margin_emu: {right_margin}",
        f"  top_margin_emu: {title_y}",
        f"  tracker_y_emu: {max(title_y - 107000, 75000)}",
        f"  title_y_emu: {title_y}",
        f"  subtitle_y_emu: {title_y + 720000}",
        f"  header_line_y_emu: {header_line_y}",
        f"  content_start_y_emu: {content_start_y}",
        f"  footer_line_y_emu: {footer_y}",
        f"  footer_y_emu: {footer_y + 45000}",
        "",
        "placeholders:",
        f"  title: {placeholder_map.get('title', 0)}",
        f"  subtitle: {placeholder_map.get('subtitle', 1)}",
    ]
    if "tracker" in placeholder_map:
        config_lines.append(f"  tracker: {placeholder_map['tracker']}")
    if "source" in placeholder_map:
        config_lines.append(f"  source: {placeholder_map['source']}")

    config_lines.extend(
        [
            "",
            "default_colors:",
            '  body_text: "tx1"',
            '  col_header: "tx1"',
            '  col_superheader: "tx1"',
            '  row_header: "accent1"     # adjust: which theme slot is your accent color?',
            '  row_superheader: "tx1"',
            '  divider: "tx1"',
            '  link: "accent1"',
            "",
            "dividers:",
            "  header_pt: 1.5",
            "  row_pt: 0.5",
            "  footer_pt: 0.5",
            "",
            "# Bullet hierarchy — extracted from the slide master lstStyle.",
            "# Run: pptx xml <template> 1 <placeholder> to inspect lstStyle levels.",
            "# Adjust bullet chars, margins, and spacing to match your template.",
            "bullets:",
            "  def_tab_sz_emu: 914354",
            "  bu_font:",
            f'    typeface: "{body_font}"',
            '    pitch_family: "34"',
            '    charset: "0"',
            "  def_rpr:",
            "    size_pt: 12",
            "    kern_pt: 12",
            '    scheme: "tx1"',
            '    latin: "+mn-lt"',
            f'    cs: "{body_font}"',
            '    cs_pitch_family: "34"',
            '    cs_charset: "0"',
            "  levels:",
            "    - level: 1",
            '      bullet: ""',
            "      mar_l_emu: 0",
            "      indent_emu: 0",
            "      spc_bef_pt: 5.0",
            "      spc_aft_pt: 0.0",
            "      ln_spc_pct: 114000",
            "    - level: 2",
            '      bullet: "•"',
            "      mar_l_emu: 228600",
            "      indent_emu: -228600",
            "      spc_bef_pt: 2.5",
            "      spc_aft_pt: 0.0",
            "      ln_spc_pct: 114000",
            "    - level: 3",
            '      bullet: "–"',
            "      mar_l_emu: 457200",
            "      indent_emu: -228600",
            "      spc_bef_pt: 1.25",
            "      spc_aft_pt: 0.0",
            "      ln_spc_pct: 114000",
            "    - level: 4",
            '      bullet: "»"',
            "      mar_l_emu: 685800",
            "      indent_emu: -228600",
            "      spc_bef_pt: 1.25",
            "      spc_aft_pt: 0.0",
            "      ln_spc_pct: 114000",
            "    - level: 5",
            '      bullet: "›"',
            "      mar_l_emu: 914400",
            "      indent_emu: -228600",
            "      spc_bef_pt: 1.25",
            "      spc_aft_pt: 0.0",
            "      ln_spc_pct: 114000",
            "    - level: 6",
            '      bullet: "◦"',
            "      mar_l_emu: 1143000",
            "      indent_emu: -228600",
            "      spc_bef_pt: 0.0",
            "      spc_aft_pt: 0.0",
            "      ln_spc_pct: 114000",
            "    - level: 7",
            '      bullet: ""',
            "      mar_l_emu: 914400",
            "      indent_emu: 0",
            "      spc_bef_pt: 0.0",
            "      spc_aft_pt: 0.0",
            "      ln_spc_pct: 100000",
            "    - level: 8",
            '      bullet: "▫"',
            "      mar_l_emu: 1143000",
            "      indent_emu: -228600",
            "      spc_bef_pt: 0.0",
            "      spc_aft_pt: 0.0",
            "      ln_spc_pct: 100000",
            "    - level: 9",
            '      bullet: "▫"',
            "      mar_l_emu: 1143000",
            "      indent_emu: -228600",
            "      spc_bef_pt: 0.0",
            "      spc_aft_pt: 0.0",
            "      ln_spc_pct: 100000",
            "",
            "table_defaults:",
            "  min_row_height_in: 0.4",
            "  cell_padding_emu: 45720",
            "  header_row_height_in: 0.5",
            "  width_step_emu: 45720",
            "  default_width_in: 1.5",
            "  row_header_width_in: 1.0",
            "  moon_width_in: 0.7",
            "  bullets_width_in: 4.0",
            "  superheader_pt_boost: 2",
            "  line_spacing: 1.14",
            "  max_header_lines: 4",
            "  row_header_target_lines: 2",
            "  shape_id_start: 1000",
            "  legend:",
            "    label_pt: 8",
            "    y_offset_in: 0.30",
            "    row_height_ratio: 1.6",
            "    gap_ratio: 0.4",
            "    char_width_ratio: 0.55",
            "",
            "icons:",
            "  default_size_emu: 228600",
            "",
            "moon:",
            "  size_emu: 228600",
            "  arc_adjustments:",
            '    "100": null',
            '    "75": ["16200000", "0"]',
            '    "50": ["16200000", "10800000"]',
            '    "25": ["16200000", "5400000"]',
            '    "0": ["16200000", "16200000"]',
            "  fills:",
            "    critical: 100",
            "    full: 100",
            "    high: 75",
            '    "75": 75',
            "    medium: 50",
            '    "50": 50',
            "    low: 25",
            '    "25": 25',
            "    none: 0",
            "    empty: 0",
            "    na: 0",
            "    disabled: 0",
            "  colors:",
            '    critical: "#E5546C"',
            '    high: "#FAA082"',
            '    medium: "#E8BDAD"',
            '    low: "#CBD5E1"',
            "    none: null",
            '    na: "#CBD5E1"',
            '    disabled: "#CBD5E1"',
            "  group:",
            "    child_offset_x: 762000",
            "    child_offset_y: 1270000",
            "    child_size: 254000",
            "    line_width_emu: 9525",
            '    bg_fill: "#F8FAFC"',
            '    outline_scheme: "tx1"',
            "",
            "# Available layouts in this template:",
        ]
    )
    for name in layout_names:
        config_lines.append(f"#   - {name}")

    return "\n".join(config_lines) + "\n"
