"""Scheduler for automated commit summarization."""

import logging
from datetime import datetime
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger

from .config import ConfigManager
from .github_client import GitHubClient
from .summarizer import CommitSummarizer
from .notifier import WebhookNotifier
from .storage import SummaryStorage

logger = logging.getLogger(__name__)


class CommitWatcher:
    """Main scheduler for watching and summarizing commits."""
    
    def __init__(self, config_path: str = None):
        """Initialize commit watcher.
        
        Args:
            config_path: Path to configuration file
        """
        self.config_manager = ConfigManager(config_path)
        self.scheduler = BackgroundScheduler()
        self.running = False
    
    def start(self) -> None:
        """Start the scheduler."""
        if self.running:
            logger.warning("Scheduler is already running")
            return
        
        config = self.config_manager.load()
        
        # Parse schedule time (HH:MM format)
        hour, minute = map(int, config.schedule_time.split(':'))
        
        # Add job to scheduler with specified timezone
        self.scheduler.add_job(
            func=self.process_all_repositories,
            trigger=CronTrigger(hour=hour, minute=minute, timezone=config.timezone),
            id='daily_commit_summary',
            name='Daily Commit Summary',
            replace_existing=True
        )
        
        self.scheduler.start()
        self.running = True
        logger.info(f"Scheduler started. Will run daily at {config.schedule_time} {config.timezone}")
    
    def stop(self) -> None:
        """Stop the scheduler."""
        if not self.running:
            return
        
        self.scheduler.shutdown()
        self.running = False
        logger.info("Scheduler stopped")
    
    def process_all_repositories(self) -> None:
        """Process all configured repositories."""
        logger.info("Starting daily commit summary processing...")
        
        config = self.config_manager.load()
        
        # Initialize clients
        github_client = GitHubClient(config.github_token)
        summarizer = CommitSummarizer(
            config.llm.api_url,
            config.llm.api_key,
            config.llm.model
        )
        storage = SummaryStorage(config.summary_dir)
        
        # Process each repository
        for repo_config in config.repositories:
            try:
                self._process_repository(
                    github_client,
                    summarizer,
                    storage,
                    repo_config.name,
                    repo_config.branch,
                    repo_config.webhook_url
                )
            except Exception as e:
                logger.error(f"Error processing {repo_config.name}/{repo_config.branch}: {e}")
                continue
        
        logger.info("Daily commit summary processing completed")
    
    def _process_repository(self, github_client: GitHubClient,
                          summarizer: CommitSummarizer,
                          storage: SummaryStorage,
                          repo_name: str, branch: str,
                          webhook_url: str) -> None:
        """Process a single repository.
        
        Args:
            github_client: GitHub API client
            summarizer: Commit summarizer
            storage: Summary storage
            repo_name: Repository name (owner/repo)
            branch: Branch name
            webhook_url: Webhook URL for notifications
        """
        logger.info(f"Processing {repo_name}/{branch}...")
        
        # Fetch commits from last 24 hours
        commits = github_client.get_commits_last_24h(repo_name, branch)
        logger.info(f"Found {len(commits)} commits in {repo_name}/{branch}")
        
        # Generate summary
        summary = summarizer.summarize_commits(commits, repo_name, branch)
        
        # Save locally
        saved_path = storage.save_summary(summary, repo_name, branch)
        logger.info(f"Summary saved to {saved_path}")
        
        # Send to webhook
        notifier = WebhookNotifier(webhook_url)
        success = notifier.send_summary(summary, repo_name, branch)
        
        if success:
            logger.info(f"Summary sent to webhook for {repo_name}/{branch}")
        else:
            logger.warning(f"Failed to send summary to webhook for {repo_name}/{branch}")
    
    def run_once(self) -> None:
        """Run the processing once immediately (for testing)."""
        logger.info("Running commit summary processing once...")
        self.process_all_repositories()


def setup_logging(level: str = "INFO") -> None:
    """Setup logging configuration.
    
    Args:
        level: Logging level (DEBUG, INFO, WARNING, ERROR)
    """
    logging.basicConfig(
        level=getattr(logging, level.upper()),
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
