from __future__ import annotations

import threading
from typing import Any

from artifact_tool_v2.generated.interface.models import SpreadsheetFile, Workbook
from artifact_tool_v2.rpc.connection import get_or_create_client

_WARMUP_SHEET_NAME = "Warmup"
_TINY_PNG_DATA_URL = (
    "data:image/png;base64,"
    "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg=="
)
_CHART_TYPES = (
    "line",
    "pie",
    "bar",
    "doughnut",
    "scatter",
    "bubble",
    "radar",
    "treemap",
    "sunburst",
    "map",
    "waterfall",
    "line3D",
    "pie3D",
    "area3D",
    "bar3D",
    "funnel",
    "histogram",
    "boxWhisker",
    "stock",
    "surface3D",
    "ofPie",
    "surface",
    "pareto",
    "combo",
    "area",
)
_DRAWING_LAYOUT_PX = {
    "columnWidths": [64] * 40,
    "rowHeights": [20] * 40,
    "columnOffsets": [index * 64 for index in range(40)],
    "rowOffsets": [index * 20 for index in range(40)],
}
_DRAWING_BOUNDS_PX = {"x": 4, "y": 4, "width": 96, "height": 48}
_WARMED_FEATURES: set[str] = set()
_WARMUP_LOCK = threading.Lock()


def _populate_warmup_workbook() -> Workbook:
    workbook = Workbook.create()
    sheet = workbook.worksheets.add(_WARMUP_SHEET_NAME)

    sheet.get_range("A1:D1").values = [["Name", "Category", "Amount", "Notes"]]
    sheet.get_range("A2:C4").values = [
        ["Alpha", "Core", 12.5],
        ["Beta", "Core", 18.75],
        ["Gamma", "Edge", 9.25],
    ]
    sheet.get_range("D2").values = [["Line 1\nLine 2"]]
    sheet.get_range("C5").formulas = [["=SUM(C2:C4)"]]
    sheet.get_range("F1:F2").values = [["Category"], ["Core"]]
    sheet.get_range("K2:K9").formulas = [
        ["=SUM(C2:C4)"],
        ["=AVERAGE(C2:C4)"],
        ['=IF(C2>10,"High","Low")'],
        ['=TEXT(C2,"0.00")'],
        ["=DATE(2026,1,1)"],
        ['=XLOOKUP("Alpha",A2:A4,C2:C4)'],
        ["=BIN2HEX(10)"],
        ["=EFFECT(0.05,12)"],
    ]
    sheet.get_range("L2").formulas = [["=FILTER(A2:A4,C2:C4>10)"]]

    header = sheet.get_range("A1:D1")
    header.format.font.bold = True
    header.format.horizontal_alignment = "center"
    header.format.fill.color = "#D9EAF4"

    amounts = sheet.get_range("C2:C5")
    amounts.format.number_format = "0.00"
    amounts.format.horizontal_alignment = "right"

    notes = sheet.get_range("D2")
    notes.format.wrap_text = True

    workbook.get_style_registry().register_differential_format(
        {"font": {"bold": True, "color": "#111827"}, "fill": "#FDE68A"}
    )
    workbook.recalculate()
    sheet.get_range("A:D").format.autofit_columns()
    sheet.get_range("1:5").format.autofit_rows()
    return workbook


def _warm_render_flow(workbook: Workbook) -> None:
    workbook.render(
        {
            "sheet_name": _WARMUP_SHEET_NAME,
            "range": "A1:D5",
            "format": "png",
            "scale": 1,
        }
    )
    workbook.export(
        {
            "sheet_name": _WARMUP_SHEET_NAME,
            "range": "A1:D5",
            "format": "jpeg",
            "scale": 1,
            "quality": 0.8,
        }
    )


def _warm_range_and_formatting_flows(workbook: Workbook, sheet: Any) -> None:
    workbook.worksheets.get_sheet_count()
    workbook.worksheets.get_sheet_index(_WARMUP_SHEET_NAME)
    workbook.worksheets.get_sheet_name_by_index(0)
    workbook.worksheets.get_item_at(0)
    workbook.worksheets.get_first()
    workbook.worksheets.get_or_add(_WARMUP_SHEET_NAME)
    workbook.worksheets.get_item(_WARMUP_SHEET_NAME)
    workbook.worksheets.get_active_worksheet()
    workbook.worksheets.get_active()
    topology = workbook.worksheets.get_topology_entries()
    workbook.worksheets.sync_topology(topology)
    workbook.worksheets.to_proto()
    if sheet.sheet_id or sheet.id:
        workbook.worksheets.get_item_by_sheet_id(sheet.sheet_id or sheet.id)

    sheet.get_used_range()
    sheet.get_cell(0, 0)
    sheet.get_range_by_indexes(0, 0, 2, 2)
    _ = sheet.default_row_height
    _ = sheet.default_col_width
    _ = sheet.base_col_width
    _ = sheet.inner_xml
    _ = sheet.outer_xml

    base = sheet.get_range("A1:D5")
    base.get_address()
    base.get_row_count()
    base.get_column_count()
    base.get_row_index()
    base.get_column_index()
    base.get_range("A1:B2")
    base.get_cell(0, 0)
    base.get_row(0)
    base.get_column(0)
    base.get_range_by_indexes(0, 0, 2, 2)
    base.get_offset_range(1, 1)
    base.get_resized_range(1, 1)
    base.get_resize_range(2, 2)
    base.offset(1, 1)
    base.resize(2, 2)

    sheet.get_range("E1").write([["Computed"]])
    sheet.get_range("E2:E4").copy_from(sheet.get_range("C2:C4"), "values")
    sheet.get_range("F3:F5").copy_from(sheet.get_range("C3:C5"), "formulas")
    sheet.get_range("A1:B2").copy_to(sheet.get_range("N1:O2"), "all")
    sheet.get_range("K2").formulas_r1_c1 = [["=RC[-8]*2"]]
    sheet.get_range("K2").calculate()
    sheet.get_range("K2").formula_info()
    sheet.get_range("K2").load("values,formulas")
    _ = sheet.get_range("K2").display_formula
    _ = sheet.get_range("K2").display_formulas
    _ = sheet.get_range("K2").formula_infos
    _ = sheet.get_range("K2").raw_values
    sheet.get_range("K3:K4").write_values([[1], [2]])
    sheet.get_range("K3:K4").fill_down()
    sheet.get_range("K5:L5").values = [[3, None]]
    sheet.get_range("K5:L5").fill_right()
    sheet.get_range("K3:K5").get_last_row()
    sheet.get_range("G1:H1").merge()
    sheet.get_range("G1:H1").unmerge()
    sheet.merge_cells("G2:H2")
    sheet.unmerge_cells("G2:H2")
    sheet.get_range("I1:I4").values = [["clear"], ["me"], ["now"], [""]]
    sheet.get_range("I1:I4").clear({"applyTo": "all"})
    sheet.get_range("A1:D5").get_current_region()
    sheet.get_range("A1:D5").get_bounding_box()
    sheet.freeze_panes.freeze_rows(1)
    sheet.freeze_panes.freeze_columns(1)
    sheet.freeze_panes.unfreeze()
    sheet.show_grid_lines = False
    workbook.worksheets.set_active_worksheet(_WARMUP_SHEET_NAME)

    header = sheet.get_range("A1:D1")
    header.format.fill = {
        "type": "gradient",
        "angleDeg": 90,
        "stops": [
            {"offset": 0, "color": "accent1"},
            {"offset": 100000, "color": "accent3"},
        ],
    }
    header.format.borders = {
        "preset": "outside",
        "style": "solid",
        "color": "#444444",
    }
    sheet.get_range("A2:D4").format.borders = {
        "preset": "inside",
        "style": "solid",
        "color": "#D0D0D0",
    }
    header.format.set_font(
        {
            "bold": True,
            "italic": True,
            "color": "#123456",
            "name": "Arial",
            "size": 11,
        }
    )
    header.format.apply_border_blueprint(
        {
            "top": {"style": "solid", "weight": 1},
            "bottom": {"style": "solid", "weight": 1},
            "insideHorizontal": {"style": "dashed", "weight": 1},
        }
    )
    header.format.get_border_blueprint_snapshot()
    sheet.get_range("A1:D5").format.row_height = 24
    sheet.get_range("A1:D5").format.column_width = 14
    sheet.get_range("P1").format.row_height_px = 28
    sheet.get_range("P1").format.column_width_px = 84
    sheet.get_range("P1").format.reset()

    temp = workbook.worksheets.add("WarmupTemp")
    temp.get_range("A1:B2").values = [[1, 2], [3, 4]]
    temp.reset()
    temp.write_name("WarmupTempRenamed")
    temp.write_index(0)
    temp.delete()


def _warm_validation_and_conditional_formatting_flows(workbook: Workbook, sheet: Any) -> None:
    sheet.get_range("B2:B10").data_validation = {
        "allowBlank": True,
        "list": {
            "inCellDropDown": True,
            "source": ["Core", "Edge", "Other"],
        },
    }
    sheet.data_validations.add(
        {
            "range": "C2:C10",
            "rule": {
                "type": "whole",
                "operator": "between",
                "formula1": 1,
                "formula2": 100,
            },
            "ignoreBlanks": True,
            "inCellDropDown": True,
        }
    )
    sheet.data_validations.get_for_address("C3")

    sheet.get_range("C2:C5").conditional_formats.add(
        "dataBar",
        {
            "color": "accent5",
            "gradient": True,
            "thresholds": [
                {"type": "num", "value": 0},
                {"type": "num", "value": 25},
            ],
        },
    )
    sheet.get_range("C2:C5").conditional_formats.add_icon_set(
        {
            "iconSet": "3Arrows",
            "showValue": True,
            "thresholds": [
                {"type": "percent", "value": 0},
                {"type": "percent", "value": 33},
                {"type": "percent", "value": 67},
            ],
        }
    )
    sheet.get_range("C2:C5").conditional_formats.add_color_scale(
        {"minColor": "#DC2626", "midColor": "#FBBF24", "maxColor": "#16A34A"}
    )
    sheet.get_range("A2:A4").conditional_formats.add_custom(
        '=A2="Alpha"',
        {"font": {"bold": True, "color": "#111827"}, "fill": "#FDE68A"},
    )
    sheet.get_range("D2:D5").conditional_formats.add_data_bar({"color": "#228BE6"})
    sheet.get_range("D2:D5").conditional_formats.add_expression("D2>10", {"fill": "#D1FAE5"})
    sheet.get_range("D2:D5").conditional_formats.add_cell_is(
        {
            "operator": "greaterThan",
            "formula": 10,
            "format": {"font": {"bold": True}},
        }
    )
    sheet.get_range("D2:D5").conditional_formats.get_item_at(0)
    sheet.conditional_formattings.add(
        {
            "range": "P2:P3",
            "rule": {
                "type": "expression",
                "formula": "=P2>0",
                "format": {"fill": "#FDE68A"},
            },
        }
    )
    sheet.conditional_formattings.clear("P2:P3")

    sheet.get_range("P4").data_validation.rule = {
        "type": "whole",
        "operator": "between",
        "formula1": 1,
        "formula2": 9,
    }
    sheet.get_range("P4").data_validation.prompt = {
        "showPrompt": True,
        "title": "Warmup",
        "message": "Enter 1-9",
    }
    sheet.get_range("P4").data_validation.error_alert = {
        "showAlert": True,
        "style": "stop",
        "title": "Warmup",
        "message": "Out of range",
    }
    sheet.get_range("P4").data_validation.ignore_blanks = True
    sheet.get_range("P4").data_validation.in_cell_drop_down = True
    sheet.get_range("P4").data_validation.clear()
    sheet.data_validations.add(
        {
            "range": "P5:P6",
            "rule": {
                "type": "whole",
                "operator": "between",
                "formula1": 1,
                "formula2": 9,
            },
        }
    )
    sheet.data_validations.clear("P5:P6")
    workbook.get_conditional_formatting_render_cache(_WARMUP_SHEET_NAME)
    workbook.invalidate_conditional_formatting_cache(_WARMUP_SHEET_NAME)
    workbook.get_conditional_formatting_render_cache(_WARMUP_SHEET_NAME)


def _warm_table_sparkline_pivot_flows(workbook: Workbook, sheet: Any) -> None:
    table = sheet.tables.add("A1:D4", True, "WarmupTable")
    table.rows.add(None, [["Delta", "Core", 4.5, "Extra"]])
    table.write_show_headers(True)
    table.write_name("WarmupTableRenamed")
    table.write_style("TableStyleMedium2")
    table.write_show_totals(True)
    table.write_show_banded_rows(True)
    table.write_highlight_first_column(True)
    table.write_highlight_last_column(True)
    table.write_show_banded_columns(True)
    table.write_show_filter_button(True)
    table.show_totals = True
    table.show_banded_columns = True
    table.get_range()
    table.get_header_row_range()
    table.append_rows([["Epsilon", "Edge", 2.5, "Appended"]])
    table.get_data_rows()
    table.refresh_bounds()
    table.sync_columns_from_sheet()
    _ = table.rows.items
    sheet.tables.get_item("WarmupTableRenamed")
    sheet.tables.get_item_or_null_object("WarmupTableRenamed")
    sheet.tables.get_item_at(0)

    sparkline_group = sheet.sparkline_groups.add(
        {
            "type": "line",
            "targetRange": "J2:J5",
            "sourceData": "C2:C5",
            "axis": {"showAxis": True},
            "markers": {"show": True, "high": True, "low": True},
        }
    )
    sheet.sparkline_groups.add(
        {
            "type": "column",
            "targetRange": "J6:J9",
            "sourceData": "C2:C5",
        }
    )
    sheet.sparkline_groups.add(
        {
            "type": "stacked",
            "targetRange": "J10:J13",
            "sourceData": "C2:C5",
        }
    )
    sheet.sparkline_groups.get_all()
    sheet.sparkline_groups.get_group_for_cell("J2")
    _ = sheet.sparkline_groups.render_context
    sparkline_group.contains_cell("J2")
    sparkline_group.get_sparkline("J2")
    sparkline_group.update_render_context()
    sparkline_group.to_proto()

    sheet.get_range("M1").formulas = [["=SUM(C2:C5)"]]
    sheet.data_tables.add("M1:O4", {"rowInput": "C2", "columnInput": "C3"})

    pivot = workbook.pivot_tables.add(
        "WarmupPivot", f"{_WARMUP_SHEET_NAME}!A1:D5", f"{_WARMUP_SHEET_NAME}!Q1"
    )
    pivot.row_hierarchies.add(pivot.hierarchies.get_item("Category"))
    pivot.column_hierarchies.add(pivot.hierarchies.get_item("Name"))
    pivot.data_hierarchies.add(pivot.hierarchies.get_item("Amount"))
    pivot.filter_hierarchies.add(pivot.hierarchies.get_item("Notes"))
    pivot.rebuild_cache()
    pivot.preview()
    pivot.layout.get_data_body_range()
    pivot.layout.load("layoutType,emptyCellText")
    pivot.layout.get_cell_style_type("Q1")
    pivot.layout.get_cell_indent_level("Q1")
    pivot.hierarchies.get_item_or_null_object("Missing")
    pivot.row_hierarchies.load()
    pivot.data_hierarchies.load()
    pivot.hierarchies.get_item("Category").fields.get_item("Category").apply_filter(
        {"manualFilter": {"selectedItems": ["Core"]}}
    )
    pivot.hierarchies.get_item("Category").fields.get_item("Category").clear_all_filters()
    workbook.pivot_tables.get_item("WarmupPivot")
    workbook.pivot_tables.get_item_or_null_object("WarmupPivot")
    workbook.pivot_tables.reload()
    workbook.pivot_tables.hydrate_layouts()
    slicer = workbook.slicers.add("WarmupPivot", "Category")
    slicer.caption = "Category Filter"
    slicer.left = 10
    slicer.top = 20
    slicer.height = 144
    slicer.width = 160
    slicer.select_items(["Core"])
    slicer.clear_filters()
    workbook.slicers.get_item("Category")
    workbook.slicers.get_item_at(0)
    workbook.slicers.reload()
    workbook.slicers.synthesize_caches()


def _warm_drawing_and_image_flows(workbook: Workbook, sheet: Any, *, include_render: bool) -> None:
    chart = sheet.charts.add(
        "bar",
        {
            "from": {"row": 1, "col": 6},
            "extent": {"widthPx": 360, "heightPx": 220},
        },
    )
    chart.categories = ["Alpha", "Beta", "Gamma", "Delta"]
    series = chart.series.add("Amount")
    series.values = [12.5, 18.75, 9.25, 4.5]
    series.categories = chart.categories
    series.points.add({"idx": 0, "fill": "#DC2626"})
    series.data_label_overrides.add({"idx": 0, "text": "Alpha"})
    series.trendlines.add({"type": "linear"})
    series.error_bars.type = "percentage"
    series.error_bars.value = 5
    chart.title = "Warmup Amount"
    chart.title_text = "Warmup Amount"
    chart.has_legend = True
    chart.legend.position = "bottom"
    chart.y_axis.title = "Amount"
    chart.data_labels.show_value = True
    chart.data_table.visible = True
    chart.set_position("G2", "L12")
    chart.set_data(sheet.get_range("A1:D5"))
    chart.width = 360
    chart.height = 220
    chart.build_trendline_render_cache()
    chart.capture_anchor_snapshot()
    chart.resolve_bounds_px(_DRAWING_LAYOUT_PX)
    chart.set_preview_bounds_px(_DRAWING_BOUNDS_PX, _DRAWING_LAYOUT_PX, {})
    chart.clear_preview_bounds()
    chart.apply_bounds_px(_DRAWING_BOUNDS_PX, _DRAWING_LAYOUT_PX, {})
    chart.to_drawing_proto()
    chart.to_proto()

    shape = sheet.shapes.add(
        {
            "geometry": "rect",
            "anchor": {
                "from": {"row": 7, "col": 0},
                "extent": {"widthPx": 180, "heightPx": 80},
            },
            "fill": "accent2",
            "line": {"width": 1, "style": "dashed", "fill": "accent4"},
        }
    )
    shape.text = "Warmup shape"
    shape_snapshot = shape.capture_anchor_snapshot()
    shape.restore_anchor_snapshot(shape_snapshot)
    shape.resolve_bounds_px(_DRAWING_LAYOUT_PX)
    shape.set_preview_bounds_px(_DRAWING_BOUNDS_PX, _DRAWING_LAYOUT_PX, {})
    shape.clear_preview_bounds()
    shape.apply_bounds_px(_DRAWING_BOUNDS_PX, _DRAWING_LAYOUT_PX, {})
    shape.record_shape_set({"fill": "#16A34A"})
    shape.to_drawing_proto()
    shape.to_snapshot()
    shape.is_placeholder()
    shape.placeholder_key()
    shape.bring_to_front()
    shape.send_to_back()
    shape.to_proto()

    image = sheet.images.add(
        {
            "dataUrl": _TINY_PNG_DATA_URL,
            "anchor": {
                "from": {"row": 7, "col": 3},
                "extent": {"widthPx": 32, "heightPx": 32},
            },
        }
    )
    image_snapshot = image.capture_anchor_snapshot()
    image.restore_anchor_snapshot(image_snapshot)
    image.resolve_bounds_px(_DRAWING_LAYOUT_PX)
    image.set_preview_bounds_px({"x": 1, "y": 1, "width": 32, "height": 32}, _DRAWING_LAYOUT_PX, {})
    image.clear_preview_bounds()
    image.apply_bounds_px({"x": 2, "y": 2, "width": 32, "height": 32}, _DRAWING_LAYOUT_PX, {})
    image.to_drawing_proto()
    sheet.auto_layout_drawings(
        [shape, image],
        {
            "direction": "horizontal",
            "gap": 8,
            "frame": {"x": 0, "y": 0, "width": 400, "height": 200},
        },
    )
    workbook.create_image_asset({"dataUrl": _TINY_PNG_DATA_URL})
    workbook.from_image(
        0,
        {"dataUrl": _TINY_PNG_DATA_URL},
        "H8",
        {"widthPx": 32, "heightPx": 32},
    )
    _warm_chart_type_matrix(include_render=include_render)

    temp = workbook.worksheets.add("WarmupDrawingsTemp")
    temp.shapes.add(
        {
            "geometry": "rect",
            "anchor": {
                "from": {"row": 1, "col": 1},
                "extent": {"widthPx": 64, "heightPx": 40},
            },
        }
    )
    temp.images.add(
        {
            "dataUrl": _TINY_PNG_DATA_URL,
            "anchor": {
                "from": {"row": 1, "col": 3},
                "extent": {"widthPx": 16, "heightPx": 16},
            },
        }
    )
    temp.delete_all_drawings()
    temp.delete()

    if include_render:
        workbook.chart_to_image(0, chart.id)


def _warm_chart_type_matrix(*, include_render: bool) -> None:
    chart_workbook = Workbook.create()
    sheet = chart_workbook.worksheets.add("WarmupCharts")
    sheet.get_range("A1:D4").values = [
        ["Category", "A", "B", "C"],
        ["One", 1, 3, 2],
        ["Two", 2, 4, 3],
        ["Three", 3, 5, 4],
    ]
    chart_ids: list[str] = []
    for index, chart_type in enumerate(_CHART_TYPES):
        chart = sheet.charts.add(
            chart_type,
            {
                "from": {"row": 1 + (index % 8) * 2, "col": 6 + (index // 8) * 5},
                "extent": {"widthPx": 220, "heightPx": 140},
            },
        )
        chart.categories = ["One", "Two", "Three"]
        series = chart.series.add(f"{chart_type} series")
        series.values = [1, 2, 3]
        series.categories = chart.categories
        chart.has_legend = True
        chart.data_labels.show_value = True
        chart.to_proto()
        chart_ids.append(chart.id)

    if include_render:
        for chart_id in chart_ids:
            chart_workbook.chart_to_image(0, chart_id)


def _warm_import_export_and_inspection_flows(workbook: Workbook, sheet: Any) -> None:
    html = workbook.to_html(0, "A1:D5", {"formulas": True})
    workbook.from_html(
        0,
        html,
        "L8",
        {"applyValues": True},
    )
    workbook.from_html(
        0,
        (
            '<table><tr><th style="font-weight:bold;background:#eee">X</th>'
            "<th>Y</th></tr><tr><td>1</td><td>=A2+1</td></tr></table>"
        ),
        "L12",
        {"applyValues": True},
    )
    workbook.from_csv(
        "A,B\n1,2\n3,4",
        {"sheetName": "WarmupCSV", "anchor": "A1"},
    )
    Workbook.from_markdown(
        "| A | B |\n| - | - |\n| 1 | 2 |",
        {"sheet_name": "WarmupMarkdown"},
    )

    workbook.apply(
        [
            {
                "op": "names.range.add",
                "name": "WarmupBlock",
                "formula": f"={_WARMUP_SHEET_NAME}!$A$1:$D$5",
            }
        ]
    )
    _ = workbook.names.items
    _ = workbook.defined_names.items
    workbook.comments.set_self(
        {"id": "warmup-user", "displayName": "Warmup User", "initials": "WU"}
    )
    thread = workbook.comments.add_thread(
        {"range": sheet.get_range("A1:B2")},
        "Warmup comment",
    )
    reply = thread.add_reply("Warmup reply")
    reply.edit("Warmup reply edited")
    reply.toggle_reaction(
        "like", {"id": "warmup-user", "displayName": "Warmup User", "initials": "WU"}
    )
    reply.to_proto()
    thread.to_snapshot()
    thread.get_comment(thread.comments[0].id)
    thread.resolve({"id": "warmup-user", "displayName": "Warmup User", "initials": "WU"})
    thread.reopen()
    thread.to_proto()
    workbook.comments.get_thread(thread.id)
    workbook.comments.threads.get_by_id(thread.id)
    workbook.comments.threads.to_proto()
    workbook.comments.to_proto()

    workbook.awareness.set_active_sheet_name(_WARMUP_SHEET_NAME)
    workbook.awareness.get_sheet_state(_WARMUP_SHEET_NAME)
    workbook.awareness.set_presence_selections(
        "warmup",
        [{"sheetName": _WARMUP_SHEET_NAME, "range": "A1:B2"}],
    )
    workbook.awareness.get_selections_for_sheet(_WARMUP_SHEET_NAME)
    workbook.awareness.clear_presence_selections("warmup")
    workbook.awareness.set_dialog({"type": "custom", "payload": {"warmup": True}})
    workbook.awareness.record_missing_action({"kind": "warmup"})
    workbook.awareness.rename_sheet(_WARMUP_SHEET_NAME, _WARMUP_SHEET_NAME)
    workbook.awareness.forget_sheet("MissingWarmupSheet")
    workbook.awareness.clear_history()

    workbook.set_color_scheme({"accent1": "#2563EB", "accent2": "#16A34A"})
    _ = workbook.theme
    workbook.inspect(
        {
            "kind": "table",
            "range": f"{_WARMUP_SHEET_NAME}!A1:D8",
            "include": "values,formulas",
            "table_max_rows": 10,
            "table_max_cols": 8,
        }
    )
    workbook.find_cells({"query": "Alpha"})
    workbook.help("charts", {"include": ["index", "examples"], "maxChars": 2000})
    workbook.trace(f"{_WARMUP_SHEET_NAME}!C5")
    workbook.collect_formula_usage_stats()
    workbook.can_undo()
    workbook.can_redo()
    workbook.undo()
    workbook.redo()
    workbook.to_proto()
    Workbook.load(workbook.to_proto())
    workbook.comments.clear_self()


def _warm_collaboration_flows(workbook: Workbook, sheet: Any) -> None:
    collab_workbook = Workbook.create()
    collab_workbook.hydrate_crdt_from_proto()
    collab_workbook.get_crdt_doc()
    collab_workbook.get_collab_origins()
    workbook.queue_workbook_collab_publish()
    workbook.queue_worksheet_collab_publish(sheet.id or _WARMUP_SHEET_NAME)
    sheet.flush_collaborative_state()
    sheet.hydrate_collaborative_refs_from_proto()


def _warm_feature_flows(workbook: Workbook, *, include_render: bool) -> None:
    sheet = workbook.worksheets.get_item(_WARMUP_SHEET_NAME)
    _warm_range_and_formatting_flows(workbook, sheet)
    _warm_validation_and_conditional_formatting_flows(workbook, sheet)
    _warm_table_sparkline_pivot_flows(workbook, sheet)
    _warm_drawing_and_image_flows(workbook, sheet, include_render=include_render)
    _warm_import_export_and_inspection_flows(workbook, sheet)
    _warm_collaboration_flows(workbook, sheet)
    workbook.recalculate()


def _warm_xlsx_flow(workbook: Workbook) -> None:
    xlsx_blob = SpreadsheetFile.export_xlsx(workbook)
    SpreadsheetFile.import_xlsx(xlsx_blob)


def warm_spreadsheet_runtime(
    *,
    include_render: bool = True,
    include_xlsx: bool = True,
    include_feature_paths: bool = True,
) -> None:
    """Warm process-scoped spreadsheet runtime pieces for Python workloads.

    This function intentionally pays the major first-use costs for the Python
    spreadsheet path:

    - RPC client creation and daemon connection/startup
    - workbook creation, range mutation, formatting, formulas, recalculation,
      and autofit
    - optional local feature paths: validation, conditional formatting, tables,
      data tables, sparklines, pivots, slicers, charts, shapes, images, HTML,
      CSV, Markdown, comments, awareness, defined-name apply, workbook
      inspection/search/help, and local collaboration state setup
    - optional image render/export and all current chart type raster paths
    - optional XLSX export and import path

    The warmup is explicit and idempotent within a process. It does not warm
    workbook-specific caches for the caller's own workbook, and it does not
    remove repeated per-call work such as `Workbook.to_proto()`, style/theme
    map rebuilding, canvas/blob encoding, and export serialization. It also
    avoids external Google Sheets calls and callback-only APIs.
    """

    requested_features = {"core"}
    if include_feature_paths:
        requested_features.add("features")
        if include_render:
            requested_features.add("feature_render")
    if include_render:
        requested_features.add("render")
    if include_xlsx:
        requested_features.add("xlsx")

    with _WARMUP_LOCK:
        missing_features = requested_features.difference(_WARMED_FEATURES)
        if not missing_features:
            return

        get_or_create_client()

        workbook: Workbook | None = None
        if "core" in missing_features:
            workbook = _populate_warmup_workbook()
            _WARMED_FEATURES.add("core")
        elif missing_features.intersection({"features", "feature_render", "render", "xlsx"}):
            workbook = _populate_warmup_workbook()

        if workbook is None:
            return

        if missing_features.intersection({"features", "feature_render"}):
            _warm_feature_flows(workbook, include_render="feature_render" in missing_features)
            _WARMED_FEATURES.add("features")
            if include_render:
                _WARMED_FEATURES.add("feature_render")

        if "render" in missing_features:
            _warm_render_flow(workbook)
            _WARMED_FEATURES.add("render")

        if "xlsx" in missing_features:
            _warm_xlsx_flow(workbook)
            _WARMED_FEATURES.add("xlsx")
