"""Support bundle generation helpers."""

from __future__ import annotations

import json
import platform
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

from g_gremlin import __version__
from g_gremlin.support_context import (
    _load_sheet_state_snapshot,
    _load_support_config,
    _read_support_log_tail,
)
from g_gremlin.support_log import read_recent


@dataclass
class BundleOptions:
    include_logs: bool = True
    log_lines: int = 100
    include_config: bool = True
    include_state: bool = True
    include_command_history: bool = True
    command_history_count: int = 50


def _utc_timestamp() -> str:
    return datetime.now(timezone.utc).isoformat()


def generate_bundle(options: BundleOptions) -> dict[str, Any]:
    bundle: dict[str, Any] = {
        "$schema": "SupportBundle/v1",
        "generated_at": _utc_timestamp(),
        "environment": {
            "version": __version__,
            "python": platform.python_version(),
            "os": platform.platform(),
            "platform": platform.system(),
        },
    }

    if options.include_config:
        config = _load_support_config()
        if config is not None:
            bundle["config"] = config

    if options.include_state:
        state = _load_sheet_state_snapshot()
        if state is not None:
            bundle["state"] = state

    if options.include_logs:
        bundle["log_tail"] = _read_support_log_tail(options.log_lines)

    command_history: list[dict[str, Any]] = []
    if options.include_command_history:
        command_history = read_recent(options.command_history_count)
        bundle["command_history"] = command_history

    last_error_fingerprint = None
    for entry in reversed(command_history):
        if entry.get("error_fingerprint"):
            last_error_fingerprint = entry.get("error_fingerprint")
            break

    if last_error_fingerprint:
        bundle["last_error_fingerprint"] = last_error_fingerprint

    return bundle


def write_bundle_file(bundle: dict[str, Any], output_path: Path) -> Path:
    output_path.parent.mkdir(parents=True, exist_ok=True)
    output_path.write_text(json.dumps(bundle, indent=2), encoding="utf-8")
    return output_path
