"""Support-friendly local debug report generation for the macOS app."""

from __future__ import annotations

import subprocess
from datetime import UTC, datetime
from importlib.metadata import PackageNotFoundError, version
from pathlib import Path

import yaml

from hive_compute.app.onboarding_state import CONFIG_PATH
from hive_compute.app.runtime_config import dashboard_url
from hive_compute.app.state import AppState
from hive_compute.worker.diagnostics import read_log_tail, resolve_worker_log_paths, run_doctor
from hive_compute.worker.keychain import describe_worker_token_storage


def build_debug_report(
    state: AppState,
    *,
    config_path: Path = CONFIG_PATH,
    log_lines: int = 20,
) -> str:
    """Return a sanitized local support report for clipboard export."""
    config_summary = _load_config_summary(config_path)
    worker_id = config_summary.get("worker_id")
    checks = run_doctor(str(config_path), check_network=True)

    lines = [
        "HiveCompute Debug Report",
        f"Generated: {datetime.now(UTC).isoformat()}",
        f"App version: {_app_version()}",
        f"Config path: {config_path}",
        f"Coordinator URL: {config_summary.get('coordinator_url', 'missing')}",
        f"Dashboard URL: {dashboard_url(config_path)}",
        f"Worker ID: {worker_id or 'missing'}",
        f"Credential storage: {_credential_storage(config_summary)}",
        f"Worker state: {state.worker_state.value}",
        f"Status line: {state.status_line()}",
        f"Current job: {state.current_job or 'none'}",
        f"Shards completed: {state.shards_completed}",
        f"Pending payout USD: {state.earnings_dollars:.2f}",
        f"Payout sync status: {state.payout_sync_status_line()}",
        f"Last payout sync at: {state.last_payout_sync_at or 'never'}",
        "",
        "Doctor checks:",
    ]

    for check in checks:
        lines.append(f"- [{check.status.upper()}] {check.name}: {check.summary}")
        if check.detail:
            lines.append(f"  detail: {check.detail}")

    lines.extend(_log_sections(worker_id, log_lines))
    return "\n".join(lines).strip() + "\n"


def copy_debug_report_to_clipboard(
    state: AppState,
    *,
    config_path: Path = CONFIG_PATH,
    log_lines: int = 20,
) -> str:
    """Generate a report and copy it to the macOS clipboard."""
    report = build_debug_report(state, config_path=config_path, log_lines=log_lines)
    try:
        subprocess.run(["pbcopy"], input=report, text=True, check=True)
    except Exception as exc:
        raise RuntimeError("HiveCompute could not copy debug info to the clipboard.") from exc
    return report


def _app_version() -> str:
    try:
        return version("hive-compute")
    except PackageNotFoundError:
        return "unknown"


def _load_config_summary(config_path: Path) -> dict[str, object]:
    if not config_path.exists():
        return {}
    try:
        with config_path.open(encoding="utf-8") as fh:
            raw = yaml.safe_load(fh) or {}
    except Exception:
        return {}
    return raw if isinstance(raw, dict) else {}


def _credential_storage(config_summary: dict[str, object]) -> str:
    try:
        return describe_worker_token_storage(config_summary)
    except Exception:
        return "unknown"


def _log_sections(worker_id: object, log_lines: int) -> list[str]:
    if not isinstance(worker_id, str) or not worker_id.strip():
        return ["", "Logs:", "- worker_id missing; no log paths available"]

    sections = ["", "Logs:"]
    for stream, path in resolve_worker_log_paths(worker_id).items():
        sections.append(f"- {stream}: {path}")
        tail = read_log_tail(path, lines=log_lines)
        if not tail:
            sections.append("  (no lines available)")
            continue
        sections.append("  tail:")
        sections.extend(f"    {line}" for line in tail)
    return sections
