from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import TYPE_CHECKING

from .common import (
    ChartBounds,
    FontType,
    RenderMetrics,
    build_x_positions,
    measure_text,
)

if TYPE_CHECKING:
    from PIL import ImageDraw

TEMPERATURE_LABEL_SAMPLE = "00"
CHART_HOURS = 24


@dataclass(frozen=True)
class ChartRenderContext:
    hour_slots: list[datetime]
    x_axis_y: int
    x_positions: list[int]


def compute_x_axis_y(
    draw: ImageDraw.ImageDraw,
    font: FontType,
    chart_bottom: int,
    plot_padding: int,
) -> int:
    _, label_height, _ = measure_text(draw, font, TEMPERATURE_LABEL_SAMPLE)
    return round(chart_bottom - label_height - (3 * plot_padding))


def build_chart_context(
    draw: ImageDraw.ImageDraw,
    font: FontType,
    chart_bounds: ChartBounds,
    now: datetime,
    metrics: RenderMetrics,
) -> ChartRenderContext:
    start_hour = now.replace(minute=0, second=0, microsecond=0)
    hour_slots = [
        start_hour + timedelta(hours=offset) for offset in range(CHART_HOURS)
    ]
    x_axis_y = compute_x_axis_y(
        draw=draw,
        font=font,
        chart_bottom=chart_bounds.bottom,
        plot_padding=metrics.plot_padding,
    )
    x_positions = build_x_positions(
        chart_bounds.left,
        chart_bounds.right,
        len(hour_slots),
    )
    return ChartRenderContext(
        hour_slots=hour_slots,
        x_axis_y=x_axis_y,
        x_positions=x_positions,
    )
