"""
Script to create sonarqube_scan.bat files for all repositories with sonar-project.properties files.
"""
import os
from pathlib import Path
import re

# Configuration
REPOS_DIR = Path(r"C:\wamp64\www\sonar_scan\repos")
SCANNER_PATH = r"C:\wamp64\www\sonar_scan\sonar-scanner\bin\sonar-scanner.bat"
SONAR_HOST_URL = "https://scan.appmonitor.co.za"

def get_project_key(properties_path: Path) -> str:
    """Extract project key from sonar-project.properties file."""
    try:
        with open(properties_path, "r", encoding="utf-8") as f:
            for line in f:
                if line.strip().startswith("sonar.projectKey"):
                    return line.split("=", 1)[1].strip()
    except Exception as e:
        print(f"Error reading {properties_path}: {e}")
    return None

def create_batch_file(repo_dir: Path, project_key: str) -> bool:
    """Create sonarqube_scan.bat file in the repository directory."""
    batch_file = repo_dir / "sonarqube_scan.bat"
    
    batch_content = f"""@echo off
REM SonarQube Scan Batch File
REM Auto-generated script to run SonarQube scan for this repository

cd /d "%~dp0"

echo Pulling latest changes from git...
git pull
if errorlevel 1 (
    echo Warning: git pull failed, continuing with scan anyway...
)

echo Starting SonarQube scan for project: {project_key}
set SCANNER_PATH={SCANNER_PATH}
REM Use SONAR_TOKEN if available, otherwise fall back to SONARQUBE_TOKEN
if defined SONAR_TOKEN (
    set TOKEN=%SONAR_TOKEN%
) else (
    set TOKEN=%SONARQUBE_TOKEN%
)
REM Add trailing slash to URL and configure timeouts for plugin downloads
REM Increase download timeout to handle slow plugin downloads
"%SCANNER_PATH%" "-Dsonar.projectKey={project_key}" "-Dsonar.sources=." "-Dsonar.host.url={SONAR_HOST_URL}/" "-Dsonar.token=%TOKEN%" "-Dsonar.scanner.download.timeout=300000"

if errorlevel 1 (
    echo.
    echo Scan failed! Check the output above for errors.
    pause
    exit /b 1
) else (
    echo.
    echo Scan completed successfully!
)
"""
    
    try:
        with open(batch_file, "w", encoding="utf-8") as f:
            f.write(batch_content)
        return True
    except Exception as e:
        print(f"Error creating batch file {batch_file}: {e}")
        return False

def main():
    """Main function to process all repositories."""
    print(f"Scanning for repositories in: {REPOS_DIR}")
    
    # Find all sonar-project.properties files
    properties_files = list(REPOS_DIR.rglob("sonar-project.properties"))
    
    # Filter out files in .sonarqube subdirectories (these are generated, not source)
    properties_files = [f for f in properties_files if ".sonarqube" not in str(f)]
    
    print(f"Found {len(properties_files)} sonar-project.properties files")
    print()
    
    success_count = 0
    skip_count = 0
    error_count = 0
    
    for props_file in properties_files:
        repo_dir = props_file.parent
        project_key = get_project_key(props_file)
        
        if not project_key:
            print(f"SKIP: {repo_dir.name} - Could not extract projectKey")
            skip_count += 1
            continue
        
        # Always update batch files to ensure they use the latest format
        batch_file = repo_dir / "sonarqube_scan.bat"
        if batch_file.exists():
            print(f"UPDATE: {repo_dir.name} - Updating existing batch file")
        
        if create_batch_file(repo_dir, project_key):
            print(f"OK: {repo_dir.name} - Created batch file with projectKey: {project_key}")
            success_count += 1
        else:
            print(f"ERROR: {repo_dir.name} - Failed to create batch file")
            error_count += 1
    
    print()
    print("=" * 60)
    print(f"Summary:")
    print(f"  Successfully created: {success_count}")
    print(f"  Skipped: {skip_count}")
    print(f"  Errors: {error_count}")
    print(f"  Total processed: {len(properties_files)}")
    print("=" * 60)

if __name__ == "__main__":
    main()
