#!/usr/bin/env python3
"""
Script to update existing projects with global configurations
"""

import json
from pathlib import Path
from datetime import datetime, timezone


def apply_global_configurations_to_project(
    project_data, global_settings, backup_options
):
    """Apply global configurations to a project data dictionary"""

    # Apply global settings to schedule_config
    if "schedule_config" not in project_data:
        project_data["schedule_config"] = {}

    schedule_config = project_data["schedule_config"]

    # Add missing global settings (preserving existing values)
    schedule_config.setdefault(
        "retry_delay_hours", global_settings.get("retry_delay_hours", 1)
    )
    schedule_config.setdefault(
        "backup_timeout_minutes", global_settings.get("backup_timeout_minutes", 0)
    )
    schedule_config.setdefault(
        "min_backup_interval_minutes",
        global_settings.get("min_backup_interval_minutes", 10),
    )
    schedule_config.setdefault(
        "min_free_space_mb", global_settings.get("min_free_space_mb", 100)
    )

    # Apply backup options (only if not present)
    if "backup_options" not in project_data:
        project_data["backup_options"] = {
            "compression_level": backup_options.get("compression_level", 6),
            "include_subdirectories": backup_options.get(
                "include_subdirectories", True
            ),
            "preserve_directory_structure": backup_options.get(
                "preserve_directory_structure", True
            ),
            "hash_algorithm": backup_options.get("hash_algorithm", "md5"),
            "hash_includes": backup_options.get("hash_includes", ["timestamp", "size"]),
            "backup_type": backup_options.get("backup_type", "complete"),
            "process_priority": backup_options.get("process_priority", "low"),
            "sequential_execution": backup_options.get("sequential_execution", True),
            "filename_format": backup_options.get(
                "filename_format", "HH-MM-SS_projects.zip"
            ),
            "date_format": backup_options.get("date_format", "YYYY-MM-DD"),
        }

    return project_data


def main():
    # Load current config
    config_file = Path("config.json")
    if not config_file.exists():
        print("Error: No se encontró config.json")
        return

    with open(config_file, "r", encoding="utf-8") as f:
        config_data = json.load(f)

    global_settings = config_data.get("global_settings", {})
    backup_options = config_data.get("backup_options", {})

    print(f"Configuraciones globales cargadas:")
    print(f"  - Global settings: {list(global_settings.keys())}")
    print(f"  - Backup options: {list(backup_options.keys())}")

    # Load current projects
    projects_file = Path("projects.json")
    if not projects_file.exists():
        print("Error: No se encontró projects.json")
        return

    with open(projects_file, "r", encoding="utf-8") as f:
        projects_data = json.load(f)

    projects = projects_data.get("projects", [])
    print(f"Procesando {len(projects)} proyectos...")

    # Update each project
    updated_count = 0
    for project in projects:
        original_schedule_keys = len(project.get("schedule_config", {}))
        has_backup_options = "backup_options" in project

        # Apply global configurations
        project = apply_global_configurations_to_project(
            project, global_settings, backup_options
        )

        new_schedule_keys = len(project.get("schedule_config", {}))
        now_has_backup_options = "backup_options" in project

        if new_schedule_keys > original_schedule_keys or (
            not has_backup_options and now_has_backup_options
        ):
            updated_count += 1

    # Update metadata
    projects_data["metadata"]["last_updated"] = datetime.now(timezone.utc).isoformat()
    projects_data["metadata"]["auto_config_update"] = datetime.now(
        timezone.utc
    ).isoformat()

    # Save updated projects
    backup_file = Path("projects.json.backup")
    # Create backup
    with open(backup_file, "w", encoding="utf-8") as f:
        json.dump(projects_data, f, indent=2, ensure_ascii=False)

    # Save updated file
    with open(projects_file, "w", encoding="utf-8") as f:
        json.dump(projects_data, f, indent=2, ensure_ascii=False)

    print(f"✅ Actualización completada:")
    print(f"  - Proyectos actualizados: {updated_count}/{len(projects)}")
    print(f"  - Backup creado en: {backup_file}")
    print(f"  - Archivo actualizado: {projects_file}")

    # Verify first project
    if projects:
        first_project = projects[0]
        print(
            f"\\nVerificación del primer proyecto '{first_project.get('name', 'N/A')}':"
        )
        print(
            f"  - Schedule config keys: {list(first_project.get('schedule_config', {}).keys())}"
        )
        print(f"  - Tiene backup_options: {'backup_options' in first_project}")


if __name__ == "__main__":
    main()
