"""
Script to update the top 20 active repositories that need updates.
"""
import sys
import logging
from pathlib import Path

# Import modules
try:
    from config_manager import ConfigManager
    from bitbucket_client import BitbucketClient
    from git_manager import GitManager
except ImportError:
    from .config_manager import ConfigManager
    from .bitbucket_client import BitbucketClient
    from .git_manager import GitManager

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('update_top_repos.log'),
        logging.StreamHandler(sys.stdout)
    ]
)

logger = logging.getLogger(__name__)


def update_repositories(repos_to_update: list, repos_dir: Path, bitbucket: BitbucketClient, git_manager: GitManager):
    """
    Update specific repositories.
    
    Args:
        repos_to_update: List of repository slugs to update
        repos_dir: Path to repositories directory
        bitbucket: BitbucketClient instance
        git_manager: GitManager instance
    """
    logger.info(f"Updating {len(repos_to_update)} repositories...")
    
    updated_count = 0
    failed_count = 0
    
    for repo_slug in repos_to_update:
        logger.info(f"\nUpdating {repo_slug}...")
        repo_path = repos_dir / repo_slug
        
        if not repo_path.exists():
            logger.error(f"  [ERROR] Repository directory does not exist: {repo_slug}")
            failed_count += 1
            continue
        
        # Get clone URL from Bitbucket
        try:
            repo_info = bitbucket.get_repository_info(repo_slug)
            if not repo_info:
                logger.warning(f"  [WARN] Could not fetch repo info from Bitbucket, trying with existing remote...")
                # Try to update using existing remote
                from git import Repo
                try:
                    repo = Repo(repo_path)
                    origin = repo.remote(name="origin")
                    origin.fetch()
                    try:
                        current_branch = repo.active_branch.name
                        repo.git.pull()
                        logger.info(f"  [OK] Successfully updated {repo_slug} (branch: {current_branch})")
                        updated_count += 1
                    except Exception as e:
                        logger.warning(f"  [WARN] Could not pull {repo_slug}: {e}")
                        failed_count += 1
                except Exception as e:
                    logger.error(f"  [ERROR] Failed to update {repo_slug}: {e}")
                    failed_count += 1
                continue
            
            clone_url = bitbucket.get_clone_url(repo_info, protocol="ssh")
            if not clone_url:
                logger.error(f"  [ERROR] Could not get clone URL for {repo_slug}")
                failed_count += 1
                continue
            
            # Use GitManager to update
            result, is_first_clone = git_manager.clone_or_update(
                repo_slug=repo_slug,
                clone_url=clone_url
            )
            
            if result:
                if is_first_clone:
                    logger.info(f"  [OK] Successfully cloned {repo_slug}")
                else:
                    logger.info(f"  [OK] Successfully updated {repo_slug}")
                updated_count += 1
            else:
                logger.error(f"  [ERROR] Failed to update {repo_slug}")
                failed_count += 1
                
        except Exception as e:
            logger.error(f"  [ERROR] Unexpected error updating {repo_slug}: {e}")
            failed_count += 1
    
    return updated_count, failed_count


def main():
    """Main function to update repositories that need updates."""
    logger.info("=" * 60)
    logger.info("Updating Top 20 Active Repositories")
    logger.info("=" * 60)
    
    # Repositories that need updates (from status check)
    repos_to_update = [
        "doh_sims",
        "sawis",
        "neoafrica_qa",
        "edioverdrive",
        "ipw-php",
        "superbowl"
    ]
    
    try:
        # Load configuration
        config = ConfigManager()
        
        # Validate required configuration
        if not config.get("bitbucket.workspace"):
            logger.error("Bitbucket workspace not configured")
            sys.exit(1)
        
        has_api_token = bool(config.get("bitbucket.api_token"))
        has_app_password = bool(config.get("bitbucket.app_password"))
        
        if not config.get("bitbucket.username"):
            logger.error("Bitbucket username/email not configured")
            sys.exit(1)
        
        if not has_api_token and not has_app_password:
            logger.error("Bitbucket authentication not configured")
            sys.exit(1)
        
        # Initialize components
        bitbucket = BitbucketClient(
            workspace=config.get("bitbucket.workspace"),
            username=config.get("bitbucket.username"),
            app_password=config.get("bitbucket.app_password") if not has_api_token else None,
            api_token=config.get("bitbucket.api_token")
        )
        
        git_manager = GitManager(
            repos_dir=config.get("scanning.repos_dir")
        )
        
        repos_dir = Path(config.get("scanning.repos_dir"))
        
        # Update repositories
        updated_count, failed_count = update_repositories(
            repos_to_update, repos_dir, bitbucket, git_manager
        )
        
        # Print summary
        logger.info("\n" + "=" * 60)
        logger.info("Update Summary")
        logger.info("=" * 60)
        logger.info(f"Total repositories to update: {len(repos_to_update)}")
        logger.info(f"  [OK] Successfully updated: {updated_count}")
        logger.info(f"  [ERROR] Failed: {failed_count}")
        logger.info("=" * 60)
        
        if failed_count > 0:
            sys.exit(1)
        else:
            logger.info("\n[SUCCESS] All repositories updated successfully!")
            sys.exit(0)
            
    except Exception as e:
        logger.error(f"Unexpected error: {e}", exc_info=True)
        sys.exit(1)


if __name__ == "__main__":
    main()
