from dataclasses import dataclass
from typing import ClassVar

import pandas as pd

from .base import SimStadtResults, detect_decimal
from .kpi import KPI
from .providers import Providers


@dataclass(repr=False)
class PhotovoltaicResults(SimStadtResults):
    """Results for Photovoltaic (PV) workflows."""

    supported_providers: ClassVar[list[str]] = [
        Providers.PHOTOVOLTAIC,
        Providers.PHOTOVOLTAIC_FINANCE,
        Providers.PHOTOVOLTAIC_WITH_SHADOW,
    ]
    csv_identifier = "_pv_potential"

    def _count_header_lines(self) -> int:
        count = 0
        with open(self.csv_path) as csv:
            for line in csv:
                if line.startswith("Building ID"):
                    return count
                count += 1
        raise ValueError(f"Header not found in {self.csv_path}")

    def _parse_results(self) -> pd.DataFrame:
        csv_decimal = detect_decimal(self.csv_path, 4, "Latitude")
        header_length = self._count_header_lines()
        df = pd.read_csv(
            self.csv_path,
            skiprows=list(range(header_length)) + [header_length + 1],
            sep=";",
            decimal=csv_decimal,
        )
        df = df.rename(columns={"Area": "Roof area for PV"})
        return df.dropna(axis=1, how="all")

    @property
    def kpis(self) -> list[KPI]:
        sums = [("Roof area for PV", "m²"), ("PV potential nominal power", "kWp"), ("PV potential yield", "MWh / a")]
        averages = [("Irradiance in module plane", "W / m²"), ("PV specific yield", "kWh / (kWp · a)")]
        return self._prepare_kpis(sums, averages)
