"""
Simple storage management extracted from Phase 4.

Provides basic storage cleanup and tracking with smart defaults.
"""

import shutil
from pathlib import Path
from typing import List, Dict


class SimpleStorageManager:
    """Basic storage management extracted from Phase 4"""

    def __init__(self, run_dir: Path):
        self.run_dir = run_dir
        self.org_dir = run_dir.parent.parent.parent  # run_dir/../../.. = org_dir

    def cleanup_old_runs(self, keep_runs: int = 5) -> dict:
        """Simple cleanup with smart defaults (extracted from Phase 4)"""
        runs_dir = self.org_dir / "billing" / "runs"
        if not runs_dir.exists():
            return {"cleaned": 0, "error": "No runs directory"}

        # Get run directories sorted by name (timestamp)
        run_dirs = sorted(
            [d for d in runs_dir.iterdir() if d.is_dir()],
            key=lambda x: x.name,
            reverse=True,
        )

        # Keep most recent runs, cleanup older ones
        cleanup_candidates = run_dirs[keep_runs:]
        cleaned = []

        for old_run in cleanup_candidates:
            # Simple cleanup - no complex policies
            if self._should_cleanup(old_run):
                size_gb = self._calculate_size(old_run)
                try:
                    shutil.rmtree(old_run)
                    cleaned.append({"path": str(old_run), "size_gb": size_gb})
                except Exception as e:
                    print(f"Failed to cleanup {old_run}: {e}")

        return {"cleaned": len(cleaned), "freed_gb": sum(c["size_gb"] for c in cleaned)}

    def get_storage_usage(self) -> dict:
        """Basic storage information (extracted from Phase 4)"""
        return {
            "current_run_size_gb": self._calculate_size(self.run_dir),
            "total_org_size_gb": self._calculate_size(self.org_dir),
            "runs_count": len(list((self.org_dir / "billing" / "runs").glob("*")))
            if (self.org_dir / "billing" / "runs").exists()
            else 0,
        }

    def _should_cleanup(self, run_dir: Path) -> bool:
        """Simple cleanup rules (from Phase 4)"""
        # Don't cleanup if marked as important
        if (run_dir / ".preserve").exists():
            return False
        if (run_dir / "IMPORTANT").exists():
            return False
        if "important" in run_dir.name.lower():
            return False
        return True

    def _calculate_size(self, directory: Path) -> float:
        """Calculate directory size in GB (from Phase 4)"""
        total_size = 0
        try:
            for file_path in directory.rglob("*"):
                if file_path.is_file():
                    total_size += file_path.stat().st_size
        except (OSError, PermissionError):
            pass
        return total_size / (1024**3)
