"""Local storage for commit summaries."""

import os
import logging
from datetime import datetime
from pathlib import Path
from typing import Optional

logger = logging.getLogger(__name__)


class SummaryStorage:
    """Stores summaries locally by date."""
    
    def __init__(self, base_dir: str = "summaries"):
        """Initialize storage.
        
        Args:
            base_dir: Base directory for storing summaries
        """
        self.base_dir = Path(base_dir)
        self.base_dir.mkdir(parents=True, exist_ok=True)
    
    def save_summary(self, summary: str, repo_name: str, branch: str,
                    date: Optional[datetime] = None) -> str:
        """Save summary to local file.
        
        Args:
            summary: Summary content
            repo_name: Repository name (owner/repo)
            branch: Branch name
            date: Date for the summary (defaults to today)
            
        Returns:
            Path to saved file
        """
        if date is None:
            date = datetime.now()
        
        # Create directory structure: summaries/YYYY-MM/DD/
        year_month = date.strftime("%Y-%m")
        day = date.strftime("%d")
        
        dir_path = self.base_dir / year_month / day
        dir_path.mkdir(parents=True, exist_ok=True)
        
        # Create filename: owner-repo-branch.md
        safe_repo_name = repo_name.replace('/', '-')
        safe_branch = branch.replace('/', '-')
        filename = f"{safe_repo_name}-{safe_branch}.md"
        
        file_path = dir_path / filename
        
        # Save with metadata header
        content = self._add_metadata(summary, repo_name, branch, date)
        
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        
        logger.info(f"Saved summary to {file_path}")
        return str(file_path)
    
    def _add_metadata(self, summary: str, repo_name: str, branch: str,
                     date: datetime) -> str:
        """Add metadata header to summary.
        
        Args:
            summary: Original summary
            repo_name: Repository name
            branch: Branch name
            date: Summary date
            
        Returns:
            Summary with metadata header
        """
        metadata = f"""---
repository: {repo_name}
branch: {branch}
date: {date.strftime("%Y-%m-%d")}
generated_at: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
---

"""
        return metadata + summary
    
    def get_summary(self, repo_name: str, branch: str, 
                   date: Optional[datetime] = None) -> Optional[str]:
        """Retrieve a saved summary.
        
        Args:
            repo_name: Repository name (owner/repo)
            branch: Branch name
            date: Date of the summary (defaults to today)
            
        Returns:
            Summary content or None if not found
        """
        if date is None:
            date = datetime.now()
        
        year_month = date.strftime("%Y-%m")
        day = date.strftime("%d")
        
        safe_repo_name = repo_name.replace('/', '-')
        safe_branch = branch.replace('/', '-')
        filename = f"{safe_repo_name}-{safe_branch}.md"
        
        file_path = self.base_dir / year_month / day / filename
        
        if not file_path.exists():
            return None
        
        with open(file_path, 'r', encoding='utf-8') as f:
            return f.read()
    
    def list_summaries(self, repo_name: Optional[str] = None,
                      branch: Optional[str] = None) -> list:
        """List all saved summaries.
        
        Args:
            repo_name: Filter by repository name (optional)
            branch: Filter by branch name (optional)
            
        Returns:
            List of summary file paths
        """
        summaries = []
        
        for file_path in self.base_dir.rglob("*.md"):
            if repo_name or branch:
                filename = file_path.stem
                if repo_name:
                    safe_repo_name = repo_name.replace('/', '-')
                    if not filename.startswith(safe_repo_name):
                        continue
                if branch:
                    safe_branch = branch.replace('/', '-')
                    if not filename.endswith(safe_branch):
                        continue
            
            summaries.append(str(file_path))
        
        return sorted(summaries, reverse=True)
