from __future__ import annotations

from dataclasses import dataclass
from datetime import timedelta
from pathlib import Path

from .config import ROOT
from .history import now_local


@dataclass(frozen=True)
class CleanupResult:
    retention_days: int
    scanned_files: int
    deleted_files: int
    deleted_bytes: int


def cleanup_old_plans(retention_days: int = 7) -> CleanupResult:
    cutoff = now_local() - timedelta(days=max(retention_days, 0))
    plans_root = ROOT / "clients"
    scanned = 0
    deleted = 0
    deleted_bytes = 0
    if not plans_root.exists():
        return CleanupResult(retention_days, scanned, deleted, deleted_bytes)

    for plans_dir in plans_root.glob("*/plans"):
        if not plans_dir.is_dir():
            continue
        for path in plans_dir.iterdir():
            if path.suffix.lower() not in {".json", ".md"}:
                continue
            scanned += 1
            try:
                modified = now_local().fromtimestamp(path.stat().st_mtime, tz=now_local().tzinfo)
            except OSError:
                continue
            if modified >= cutoff:
                continue
            try:
                size = path.stat().st_size
                path.unlink()
            except OSError:
                continue
            deleted += 1
            deleted_bytes += size
    return CleanupResult(retention_days, scanned, deleted, deleted_bytes)


def plan_retention_days(global_rules: dict, default: int = 7) -> int:
    cleanup_rules = global_rules.get("plan_cleanup", {})
    try:
        return int(cleanup_rules.get("retention_days", default))
    except (TypeError, ValueError):
        return default


def print_cleanup_result(result: CleanupResult) -> None:
    if result.deleted_files <= 0:
        return
    mb = result.deleted_bytes / 1024 / 1024
    print(
        "\nAutoczyszczenie planow: "
        f"usunieto {result.deleted_files} plikow starszych niz {result.retention_days} dni "
        f"({mb:.2f} MB)."
    )
