import re

from . import models

_SUFFIX_RE = re.compile(r"^(?P<base>.*?)\s*\((?P<types>[a-z/]+)\)$")


def _migrate_existing_holiday_type(env):
    # Note: adding xeno_holiday_type with a default backfills every
    # existing row to 'public' at the schema level before this hook runs,
    # so this can't filter on xeno_holiday_type being unset -- it has to
    # parse every record's name and overwrite the default with whatever
    # the embedded "(public)"/"(company)" suffix actually says.
    Leaves = env["resource.calendar.leaves"]
    for record in Leaves.search([]):
        match = _SUFFIX_RE.match(record.name or "")
        if not match:
            continue
        types = match.group("types").split("/")
        if "public" not in types and "company" not in types:
            continue
        holiday_type = "public" if "public" in types else "company"
        record.write({"xeno_holiday_type": holiday_type, "name": match.group("base")})
