"""
Cleanup Module

Handles cleaning up temp files at end of session.
"""

import shutil
from pathlib import Path
from typing import Optional

from hooks.config import (
    TEMP_DIR,
    TEMP_FILES_TO_CLEAN,
    KEEP_LAST_N_LOG_LINES,
    CLEANUP_ON_STOP,
    get_project_claude_logs_dir,
)


def cleanup_project_temp_files(project_path: str) -> int:
    """
    Clean up temp files from a project's .claude/logs directory.

    Args:
        project_path: Path to the project

    Returns:
        Number of files cleaned
    """
    if not CLEANUP_ON_STOP:
        return 0

    if not project_path:
        print("[CodeContext] No project path, skipping cleanup")
        return 0

    logs_dir = get_project_claude_logs_dir(project_path)
    if not logs_dir.exists():
        return 0

    cleaned = 0
    for filename in TEMP_FILES_TO_CLEAN:
        file_path = logs_dir / filename
        if file_path.exists():
            try:
                if KEEP_LAST_N_LOG_LINES > 0 and filename.endswith('.log'):
                    # Keep last N lines
                    _truncate_log_file(file_path, KEEP_LAST_N_LOG_LINES)
                    print(f"[CodeContext] Truncated {filename} to last {KEEP_LAST_N_LOG_LINES} lines")
                else:
                    # Delete entirely
                    file_path.unlink()
                    print(f"[CodeContext] Cleaned {filename}")
                cleaned += 1
            except Exception as e:
                print(f"[CodeContext] Failed to clean {filename}: {e}")

    return cleaned


def _truncate_log_file(file_path: Path, keep_lines: int) -> None:
    """
    Truncate a log file to keep only the last N lines.

    Args:
        file_path: Path to the log file
        keep_lines: Number of lines to keep
    """
    try:
        lines = file_path.read_text(encoding='utf-8').splitlines()
        if len(lines) > keep_lines:
            kept_lines = lines[-keep_lines:]
            file_path.write_text('\n'.join(kept_lines) + '\n', encoding='utf-8')
    except Exception as e:
        print(f"[CodeContext] Truncate error: {e}")


def cleanup_autocoder_temp() -> int:
    """
    Clean up the global ~/.autocoder/temp directory.

    Returns:
        Number of files cleaned
    """
    if not TEMP_DIR.exists():
        return 0

    cleaned = 0
    for file_path in TEMP_DIR.iterdir():
        if file_path.is_file():
            try:
                file_path.unlink()
                cleaned += 1
            except Exception as e:
                print(f"[CodeContext] Failed to clean {file_path.name}: {e}")

    return cleaned


def cleanup_chunk_state() -> bool:
    """
    Remove the chunk_state.json file after processing.

    Returns:
        True if cleaned, False otherwise
    """
    from hooks.config import MEMORY_DIR

    state_file = MEMORY_DIR / "chunk_state.json"
    if state_file.exists():
        try:
            state_file.unlink()
            return True
        except Exception as e:
            print(f"[CodeContext] Failed to clean chunk_state: {e}")
    return False


def cleanup_all(project_path: Optional[str] = None) -> dict:
    """
    Run all cleanup operations.

    Args:
        project_path: Optional project path for project-specific cleanup

    Returns:
        Dict with cleanup stats
    """
    stats = {
        "project_files": 0,
        "temp_files": 0,
        "chunk_state": False,
    }

    if project_path:
        stats["project_files"] = cleanup_project_temp_files(project_path)

    stats["temp_files"] = cleanup_autocoder_temp()
    stats["chunk_state"] = cleanup_chunk_state()

    total = stats["project_files"] + stats["temp_files"] + (1 if stats["chunk_state"] else 0)
    if total > 0:
        print(f"[CodeContext] Cleanup complete: {total} items")

    return stats


# CLI for testing
if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="Cleanup temp files")
    parser.add_argument("--project", type=str, help="Project path")
    parser.add_argument("--all", action="store_true", help="Run all cleanup")
    parser.add_argument("--temp-only", action="store_true", help="Clean only ~/.autocoder/temp")

    args = parser.parse_args()

    if args.all:
        stats = cleanup_all(args.project)
        print(f"Stats: {stats}")
    elif args.temp_only:
        count = cleanup_autocoder_temp()
        print(f"Cleaned {count} temp files")
    elif args.project:
        count = cleanup_project_temp_files(args.project)
        print(f"Cleaned {count} project temp files")
    else:
        print("Usage: python cleanup.py --all --project /path/to/project")
        print("       python cleanup.py --temp-only")
