# pldatacli/commands/generate_yaml.py
"""
Utilities to generate YAML pipeline files from CLI arguments.
"""

from datetime import datetime
from pathlib import Path
import yaml
import typer


def _write_yaml_with_header(data: dict, yaml_path: Path, command: str) -> None:
    """Write YAML with nice header comment."""
    now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    header = f"""# Generated by: pldatacli {command} --generate-yaml
# Date: {now}
# File: {yaml_path.name}

# You can run this pipeline later with:
#   pldatacli run {yaml_path.name}

"""

    # Make sure parent directories exist
    yaml_path.parent.mkdir(parents=True, exist_ok=True)

    with yaml_path.open("w", encoding="utf-8") as f:
        f.write(header)
        yaml.safe_dump(
            data,
            f,
            sort_keys=False,
            allow_unicode=True,
            indent=2,
            default_flow_style=False,
        )

    typer.secho(
        f"→ YAML pipeline saved → {yaml_path}", fg=typer.colors.GREEN, bold=True
    )


def generate_query_yaml(
    file: Path,
    filter: list[str] | None,
    truncate: str | None,
    groupby: list[str] | None,
    agg: list[str] | None,
    sort: list[str] | None,
    head: int | None,
    tail: int | None,
    round_digits: int | None,
    output: Path | None,  # the --output from query command
    yaml_path: Path,
) -> None:
    """Generate YAML file equivalent to a `query` command invocation."""
    data = {
        "file": str(file.resolve()),
    }

    if filter:
        data["filter"] = filter
    if truncate:
        data["truncate"] = truncate
    if groupby:
        data["groupby"] = groupby
    if agg:
        data["agg"] = agg
    if sort:
        data["sort"] = sort
    if head is not None:
        data["head"] = head
    if tail is not None:
        data["tail"] = tail
    if round_digits is not None:
        data["round"] = round_digits
    if output is not None:
        data["output"] = str(output.resolve())

    _write_yaml_with_header(data, yaml_path, command="query")


def generate_pivot_yaml(
    file: Path,
    truncate: str | None,
    on: str,
    index: list[str],
    values: str,
    aggregate: str,
    round_digits: int | None,
    output: Path | None,
    yaml_path: Path,
) -> None:
    """Generate YAML file equivalent to a `pivot` command invocation."""
    data = {
        "file": str(file.resolve()),
    }

    if truncate:
        data["truncate"] = truncate

    pivot_config = {
        "column": on,  # matches current --on flag
        "index": index if len(index) > 1 else (index[0] if index else None),
        "values": values,
        "aggregate": aggregate,
    }
    data["pivot"] = pivot_config

    if round_digits is not None:
        data["round"] = round_digits
    if output is not None:
        data["output"] = str(output.resolve())

    _write_yaml_with_header(data, yaml_path, command="pivot")
