# -*- coding: utf-8 -*-
import subprocess
from typing import Optional

from ..constant import DEFAULT_REPORT_FILE_TYPE, ALLOWED_FILE_TYPES


def render_notebook_to_output_file_type(
        working_directory: str,
        notebook_file_name: str,
        file_type: Optional[str] = DEFAULT_REPORT_FILE_TYPE
) -> bool:
    """
    Renders a notebook to Output File Type using Quarto.

    Args:
        working_directory (str): Directory from which the command is executed
        notebook_file_name (str): Name of the notebook file to render.

    Returns:
        bool: True if Output File generation was successful, False otherwise.
    """
    if file_type.lower() not in ALLOWED_FILE_TYPES:
        raise ValueError(f"invalid file type: {file_type}")
    # Build Quarto command with options
    quarto_cmd = ["quarto", "render", f"files/clean/{notebook_file_name}", "--to", f"{str(file_type).lower()}"]

    # Render the notebook to output file type using Quarto from (CWD) the reports directory
    try:
        subprocess.run(
            quarto_cmd,
            cwd=working_directory,
            check=True
        )
        return True
    except subprocess.CalledProcessError as e:
        print(f"Quarto render failed: {e}")
        raise


def render_dagstermill_notebook_to_output_file_type(
        working_directory: str,
        executed_notebook_file_name: str,
        file_type: Optional[str] = DEFAULT_REPORT_FILE_TYPE
) -> bool:
    """
    Renders a Dagstermill-executed notebook to file type (PDF/DocX/etc) using Quarto.

    Args:
        working_directory (str): Directory from which the command is executed
        executed_notebook_file_name (str): Name of the executed notebook file to render.
        file_type (str): File type of the rendered document (PDF/DocX/etc.)deac

    Returns:
        bool: True if output file type generation was successful, False otherwise.
    """
    return render_notebook_to_output_file_type(
        working_directory=working_directory,
        notebook_file_name=executed_notebook_file_name,
        file_type=file_type,
    )
