"""Nox configuration file."""
from pathlib import Path
from tempfile import TemporaryDirectory
from shutil import copytree, copy

from nox import Session, session

_LOCALES = ["fr"]

@session()
def lint(session: Session) -> None:
    session.install("ruff")
    session.run("ruff", "check", "--fix")
    session.run("ruff", "format")


@session()
def mypy(session: Session) -> None:
    session.install("-e", ".[dev]", "mypy", "types-PyYAML", "types-Markdown")
    session.run("mypy")


@session
def build(session: Session) -> None:
    """Run unit tests."""
    session.install(
        "nodeenv",
        "git+https://git.frog-collective.com/collectivit/jean-web",
        "babel",
        "jinja2"
    )

    session.run_always("nodeenv", "-p")
    session.run_always("npm", "install", "-g", "sass")

    session.log("Building css...")
    session.run("npx", "sass", "src/style.scss", "build/style.css", "--style=compressed")

    session.log("Copying static files to build directory...")
    copytree("src/assets", "build", dirs_exist_ok=True)
    copy("config/.htaccess", "build")

    with TemporaryDirectory() as locale_dir:
        for locale in _LOCALES:
            output_dir = Path(locale_dir) / locale / "LC_MESSAGES"
            output_dir.mkdir(exist_ok=True, parents=True)

            session.run(
                "pybabel",
                "compile",
                f"--input-file=locale/{locale}/LC_MESSAGES/site.po",
                f"--output-file={output_dir}/site.mo",
                "--use-fuzzy"
            )

        session.log("Building website...")
        session.run(
            "jweb", "build",
            env={
                'FROG_LOCALE_DIR': str(locale_dir)
            }
        )

@session
def extract_messages(session: Session) -> None:
    session.install("babel", "jinja2", "setuptools")

    with TemporaryDirectory() as tmp_dir:
        messages_file = Path(tmp_dir) / "messages.po"
        session.run("pybabel", "extract", "--mapping", "babel.cfg", f"--output-file={messages_file}", ".")
        session.run("pybabel", "update", "--domain=site", f"--input-file={messages_file}", "--output-dir=locale")

@session
def compile_messages(session:  Session) -> None:
    session.install("babel", "jinja2")

@session()
def devenv(session: Session) -> None:
    session.install("-e", ".[dev]")
