#!/usr/bin/env python3
"""Header component for the UI."""

import curses
from datetime import datetime
from typing import Optional

from aitop.version import __author__, __version__

from ..display import Display


class HeaderComponent:
    """Renders the application header."""

    def __init__(self, display: Display):
        """Initialize the header component.

        Args:
            display: Display instance
        """
        self.display = display

    def render(
        self,
        gpu_vendor: str,
        y: int = 0,
        attr: Optional[int] = None,
        current_tab: Optional[str] = None,
    ) -> int:
        """Render the header.

        Args:
            gpu_vendor: Unused compatibility parameter for legacy callers.
            y: Starting Y coordinate (ignored, uses layout system)
            attr: Custom attribute override
            current_tab: Optional active tab label

        Returns:
            Next Y coordinate
        """
        if attr is None:
            attr = self.display.get_theme_attr("header")

        # Get header layout from layout system
        layout = self.display.layout.calculate()
        header_rect = layout["header"]

        muted_attr = self.display.get_theme_attr("muted")
        accent_attr = self.display.get_theme_attr("accent") | curses.A_BOLD
        chip_active_attr = self.display.get_theme_attr("chip_active")

        current_time = datetime.now().strftime("%H:%M:%S")
        del gpu_vendor  # Vendor chip intentionally removed from header.
        tab_label = (current_tab or "OVERVIEW").upper()

        left_anchor = "AITop"
        self.display.safe_addstr(header_rect.y, 1, left_anchor, accent_attr)

        x = 1 + len(left_anchor) + 2
        chips = [(f"[{tab_label}]", chip_active_attr)]

        right_text = f"{current_time} | v{__version__} | (c) {__author__}"
        header_width = max(0, header_rect.width)
        right_x = max(0, header_width - len(right_text) - 1)
        if right_x > 0:
            self.display.safe_addstr(header_rect.y, right_x, right_text, muted_attr)

        for chip_text, chip_style in chips:
            if x + len(chip_text) + 1 >= right_x:
                break
            self.display.safe_addstr(header_rect.y, x, chip_text, chip_style)
            x += len(chip_text) + 1

        return header_rect.bottom
