import logging
from pathlib import Path
from typing import Optional

import typer
from typing_extensions import Annotated

from yamlex.api.splitter import split_yaml
from yamlex.api.util import (
    adjust_root_logger,
    get_default_extension_dir_path,
    get_default_extension_source_dir_path,
    is_manually_created,
    write_file,
)
from yamlex.cli.common_flags import (
    no_comment_flag,
    force_flag,
    verbose_flag,
    quiet_flag,
)


logger = logging.getLogger(__name__)


def split(
    source: Annotated[
        Optional[Path],
        typer.Option(
            "--source",
            "-s",
            help="Path to source extension.yaml file.",
            show_default="[default: extension/extension.yaml or src/extension/extension.yaml]",
            dir_okay=False,
            file_okay=True,
            exists=True,
            readable=True,
        ),
    ] = None,
    target: Annotated[
        Optional[Path],
        typer.Option(
            "--target",
            "-t",
            help="Path to directory where split YAML source files will be stored.",
            show_default="[default: source or src/source]",
            dir_okay=True,
            file_okay=False,
            exists=True,
            writable=True,
        ),
    ] = None,
    no_comment: no_comment_flag = False,
    force: force_flag = False,
    verbose: verbose_flag = False,
    quiet: quiet_flag = False,
) -> None:
    """
    Split [i]extension.yaml[/i] file into individual components.

    Performs a "best effort" opinionated splitting. This operation does not
    affect the original extension.yaml file. Instead, it extracts components
    from it and places them into individual files within the --target folder.

    [b]Splitting multiple times[/b]:

    Theoretically, you only split once. But in practice you can do it over
    and over (not very well tested). When performing consequent splitting,
    the operation overwrites any previously generated split files, if they
    have the 'Generated by yamlex' line within them. If the target file
    does not have the comment, it is considered to be manually created and is
    not overwritten. You can still force the overwrite using the --force flag.

    [b]Do not add 'Generated with yamlex' to files when splitting[/b]:

    When splitting, you can choose to not add the 'Generated by yamlex'
    comment to the generated files by using the --no-comment flag.
    """
    adjust_root_logger(verbose, quiet)

    source = source or get_default_extension_dir_path() / "extension.yaml"
    logger.debug(f"Source file: {source}")

    target = target or get_default_extension_source_dir_path()
    logger.debug(f"Target directory: {target}")

    split_parts = split_yaml(source, target)

    for path, part in split_parts.items():
        if is_manually_created(path) and not force:
            logger.info(f"(Skipping) Part: {path}")
        else:
            should_add_comment = not no_comment
            write_file(path, part, add_comment=should_add_comment)
            logger.info(f"Part written: {path}")
