"""CLI command for viewing operation history."""
from datetime import datetime, timedelta, timezone

import click

from k4s.cli.state import CliState


@click.command("history")
@click.option("-n", "--last", "limit", default=None, type=int, help="Show only the last N entries.")
@click.option("--product", default=None, help="Filter by product (e.g. dataiku, nexus).")
@click.pass_context
def history(ctx, limit, product):
    """Show past k4s operations (install, configure, tls, ...).

    \b
    Examples:
      k4s history
      k4s history -n 5
      k4s history --product dataiku
    """
    state: CliState = ctx.obj["state"]
    ui = state.ui

    entries = state.history.read(limit=limit)
    if product:
        entries = [e for e in entries if e.get("product") == product.lower()]

    if not entries:
        ui.info("No history entries found.")
        return

    tr_tz = timezone(timedelta(hours=3))
    rows = []
    for e in entries:
        ts_raw = e.get("timestamp", "-")
        ts = "-"
        if isinstance(ts_raw, str) and "T" in ts_raw:
            # Stored timestamps are UTC ISO8601; render in Turkey local time (UTC+3).
            try:
                dt = datetime.fromisoformat(ts_raw.replace("Z", "+00:00"))
                ts = dt.astimezone(tr_tz).strftime("%Y-%m-%d %H:%M:%S")
            except ValueError:
                ts = ts_raw
        elif isinstance(ts_raw, str):
            ts = ts_raw
        action = e.get("action", "-")
        prod = e.get("product", "-")
        host = e.get("host") or e.get("context") or "-"
        result = e.get("result", "-")
        params = e.get("params", {})
        version = params.get("version", "")
        rows.append([ts, action, prod, host, version, result])

    ui.table(
        title="Operation history",
        columns=["time", "action", "product", "host", "version", "result"],
        rows=rows,
    )
