from __future__ import annotations

from openpyxl import Workbook
from openpyxl.worksheet.worksheet import Worksheet

from xllayout.core.grid import GridConfig
from xllayout.core.theme import LightTheme, Theme
from xllayout.layouts.summary import ExecutiveSummaryData, ExecutiveSummaryLayout


class ReportWriter:
    def __init__(self, theme: Theme | None = None, detect_collisions: bool = False) -> None:
        self.theme = theme or LightTheme()
        self.detect_collisions = detect_collisions

    def new_workbook(self) -> Workbook:
        wb = Workbook()
        # Keep workbook clean; sheets are added explicitly by layouts.
        wb.remove(wb.active)
        return wb

    def build_summary_sheet(
        self,
        wb: Workbook,
        data: ExecutiveSummaryData,
        sheet_name: str = "Summary",
        grid_config: GridConfig | None = None,
    ) -> Worksheet:
        ws = wb.create_sheet(sheet_name)
        ws.sheet_view.showGridLines = False
        ws.page_setup.fitToWidth = 1
        ws.page_setup.fitToHeight = 0

        layout = ExecutiveSummaryLayout(
            data=data,
            theme=self.theme,
            detect_collisions=self.detect_collisions,
            grid_config=grid_config,
        )
        layout.build(ws)
        return ws
