import re
from enum import Enum
from typing import List


class EpcConstructionAgeBand(Enum):
    before_1900: str = 'England and Wales: before 1900'
    from_1900_to_1929: str = 'England and Wales: 1900-1929'
    from_1930_to_1949: str = 'England and Wales: 1930-1949'
    from_1950_to_1966: str = 'England and Wales: 1950-1966'
    from_1967_to_1975: str = 'England and Wales: 1967-1975'
    from_1976_to_1982: str = 'England and Wales: 1976-1982'
    from_1983_to_1990: str = 'England and Wales: 1983-1990'
    from_1991_to_1995: str = 'England and Wales: 1991-1995'
    from_1996_to_2002: str = 'England and Wales: 1996-2002'
    from_2003_to_2006: str = 'England and Wales: 2003-2006'
    from_2007_to_2011: str = 'England and Wales: 2007-2011'
    from_2012_onwards: str = 'England and Wales: 2012 onwards'
    from_2012_to_2022: str = 'England and Wales: 2012-2022'
    from_2023_onwards: str = 'England and Wales: 2023 onwards'

    def start_year(self) -> int:
        """
        Extract the starting year of the age band.
        """
        value = self.value.lower()

        if 'before' in value:
            return 0
        match = re.search(r'(\d{4})', value)
        if not match:
            raise ValueError(f"Cannot determine start year from '{self.value}'")

        return int(match.group(1))

    @classmethod
    def from_year_onwards(cls, year: int) -> List["EpcConstructionAgeBand"]:
        """
        Return all age bands whose starting year is >= the given year.
        """
        return [
            band
            for band in cls
            if band.start_year() >= year
        ]
