"""
Jobs for the Trees extension.
"""

from __future__ import annotations

import json
from asyncio import gather
from typing import TYPE_CHECKING, override

import aiofiles
from aiofiles.os import makedirs

from betty.ancestry.person import Person
from betty.job import Job
from betty.media_type.media_types import HTML

if TYPE_CHECKING:
    from babel import Locale

    from betty.job.scheduler import Scheduler
    from betty.project import Project


class _GeneratePeopleJson(Job):
    def __init__(self, *, project: Project):
        super().__init__("trees:generate-people-json")
        self._project = project

    @override
    async def do(self, scheduler: Scheduler, /) -> None:
        await gather(
            *(
                self._generate_people_json_for_locale(scheduler, locale)
                for locale in self._project.configuration.locales.keys()  # noqa: SIM118
            )
        )

    async def _generate_people_json_for_locale(
        self, scheduler: Scheduler, locale: Locale
    ) -> None:
        url_generator = await self._project.url_generator
        localizers = await self._project.localizers
        localizer = localizers.get(locale)
        private_label = localizer._("private")
        people = {
            person.id: {
                "id": person.id,
                "label": person.label.localize(localizer)
                if person.public
                else private_label,
                "url": url_generator.generate(person, media_type=HTML),
                "parentIds": [parent.id for parent in person.parents],
                "childIds": [child.id for child in person.children],
                "private": person.private,
            }
            for person in self._project.ancestry[Person]
        }
        people_json = json.dumps(people)
        await makedirs(self._project.localize_www_directory(locale), exist_ok=True)
        async with aiofiles.open(
            self._project.localize_www_directory(locale) / "people.json",
            mode="w",
        ) as f:
            await f.write(people_json)
