import os
import subprocess
import time

def get_source_files(root_dir):
    """Récupère les fichiers et calcule la taille totale."""
    source_files = []
    total_size = 0
    for root, _, files in os.walk(root_dir):
        for file in files:
            if file.endswith(('.c', '.h')) and len(source_files)<20000:
                path = os.path.join(root, file)
                source_files.append(path)
                total_size += os.path.getsize(path)
    return source_files, total_size

def main():
    target_dir = "linux"
    if not os.path.exists(target_dir):
        print(f"Erreur: Le dossier {target_dir} n'existe pas.")
        return

    print(f"--- Analyse de {target_dir} ---")
    files, total_raw_size = get_source_files(target_dir)
    raw_mo = total_raw_size / (1024 * 1024)
    print(f"Fichiers trouvés : {len(files)}")
    print(f"Taille totale brute : {raw_mo:.2f} Mo")

    # 1. Compression avec TAR
    print("\n--- Lancement de TAR -cJf (XZ) ---")
    start_tar = time.time()
    tar_cmd = ["tar", "-cJf", "linux_sources.tar.xz", "--files-from=-"]
    process_tar = subprocess.Popen(tar_cmd, stdin=subprocess.PIPE)
    process_tar.communicate(input="\n".join(files).encode())
    end_tar = time.time()

    # 2. Compression avec CCC
    print("\n--- Lancement de CCC (Output temps réel) ---")
    print("-" * 40)
    start_ccc = time.time()
    try:
        # On laisse stdout et stderr par défaut pour voir l'output de CCC
        subprocess.run(["./ccc"] + files, check=True)
    except subprocess.CalledProcessError as e:
        print(f"\nErreur fatale CCC : {e}")
    except OSError as e:
        print(f"\nErreur système (trop de fichiers ?) : {e}")
        return
    end_ccc = time.time()
    print("-" * 40)

    # 3. Calculs finaux
    print("\n" + "="*40)
    print(f"      RÉSULTATS (Source: {raw_mo:.2f} Mo)")
    print("="*40)

    for name, filename in [("TAR.XZ", "linux_sources.tar.xz"), ("CCC", "test.ccc")]:
        if os.path.exists(filename):
            size_mo = os.path.getsize(filename) / (1024 * 1024)
            ratio = (size_mo / raw_mo) * 100
            print(f"{name:10} : {size_mo:8.2f} Mo ({ratio:5.2f}% du total)")
        else:
            print(f"{name:10} : Non généré")

    print(f"\nTemps TAR : {end_tar - start_tar:.2f}s")
    print(f"Temps CCC : {end_ccc - start_ccc:.2f}s")

if __name__ == "__main__":
    main()
