import asyncio
from pathlib import Path

import aiofiles

from ... import api
from ...api import Recipe, RecipeSerializer
from ...api import Settings
from ...api.recipe.serializer import Format
from ...api.recipe.utils import capitalise
from ...api.utils import clean_filename


async def export_recipes():
    settings = Settings.load()
    markdown_folder = settings.system.recipe_library / "md"  # todo: dedupe this
    recipes = await Recipe.load_all()
    print(f"loaded {len(recipes)} recipes")
    await asyncio.gather(
        *(_serialize(recipe, markdown_folder) for recipe in recipes)
    )
    await create_readme(
        {
            _markdown_filename(recipe, markdown_folder): recipe
            for recipe in recipes
        }
    )


async def create_readme(recipes: dict[Path, Recipe]):
    """
    Args:
        recipes: dict of markdown filenames : recipe objects
    """
    settings = Settings.load()

    readme = ["# Recipes"]

    recipes_list = []
    for md_filename in sorted(recipes):
        recipe = recipes[md_filename]
        recipes_list.append(
            f"- [{capitalise(recipe.name)}](md/{md_filename.name}) "
            f"by {recipe.author}"
        )
    recipes_list_str = "\n".join(recipes_list)
    readme.append(recipes_list_str)

    readme.append(
        f"Generated by [`yes-chef`](https://github.com/binnev/yes-chef) "
        f"version {api.__version__}"
    )

    readme_str = "\n\n".join(readme)

    async with aiofiles.open(
        settings.system.recipe_library / "README.md", "w"
    ) as file:
        await file.write(readme_str)


async def _serialize(recipe: Recipe, markdown_dir: Path):
    filename = _markdown_filename(recipe, markdown_dir)
    serialized = RecipeSerializer().serialize(recipe, Format.MARKDOWN)
    async with aiofiles.open(filename, "w") as file:
        await file.write(serialized)


def _markdown_filename(recipe: Recipe, markdown_dir: Path) -> Path:
    return clean_filename(markdown_dir / f"{recipe.name}.md")
