# SPDX-License-Identifier: AGPL-3.0-only
# Copyright (c) 2026 sol pbc

"""App-owned scheduled maintenance routines for solstone health."""

from __future__ import annotations

import argparse
import sys

from solstone.think.log_retention import PRUNE_LOGS_MAX_RUNTIME, prune
from solstone.think.maintenance import MaintenanceRoutine
from solstone.think.retention import _human_bytes
from solstone.think.utils import require_solstone


def run_prune_logs_routine(args: list[str]) -> int:
    require_solstone()
    parser = argparse.ArgumentParser(prog="journal maintenance run health:prune-logs")
    parser.add_argument("--dry-run", action="store_true")
    parser.add_argument("--days", type=int, default=None)
    ns = parser.parse_args(args)
    if ns.days is not None and ns.days < 1:
        print("prune-logs: --days must be a positive integer", file=sys.stderr)
        return 1

    result = prune(days=ns.days, dry_run=ns.dry_run)
    if not result.enabled:
        print("prune-logs: disabled (no-op)")
        return 0

    action = "would prune" if result.dry_run else "pruned"
    print(
        "prune-logs: "
        f"{action} {result.files_deleted} operational-log file(s), "
        f"{result.dirs_deleted} cache dir(s), {_human_bytes(result.bytes_freed)} "
        f"cutoff={result.cutoff_day}"
    )
    for class_name, stats in result.by_class.items():
        files = int(stats.get("files_deleted", 0))
        dirs = int(stats.get("dirs_deleted", 0))
        bytes_freed = int(stats.get("bytes_freed", 0))
        if files == 0 and dirs == 0 and bytes_freed == 0:
            continue
        print(
            f"  {class_name}: {files} file(s), {dirs} cache dir(s), "
            f"{_human_bytes(bytes_freed)}"
        )
    root_stats = result.root_task_log
    root_lines = int(root_stats.get("lines_removed", 0))
    if root_lines:
        root_action = "would compact" if result.dry_run else "compacted"
        print(
            f"  root_task_log: {root_action} {root_lines} line(s), "
            f"{_human_bytes(int(root_stats.get('bytes_freed', 0)))}"
        )
    for error in result.errors:
        hint = f" hint={error['hint']}" if error.get("hint") else ""
        print(f"  error: {error['reason']}: {error['message']}{hint}")
    return 0


ROUTINES = [
    MaintenanceRoutine(
        name="prune-logs",
        description="prune old operational logs and execution traces.",
        every="daily",
        run=run_prune_logs_routine,
        max_runtime=PRUNE_LOGS_MAX_RUNTIME,
    )
]
