"""
A mettre dans le dossier racine (contenant src/ et src/scripts et src/scripts/serveur)
Sert à scanner tous les fichiers .tex du dossier "src/" pour rechercher tous les programmes
référencés dans un QRcode, puis les copie dans le dossier "src/scripts/serveur".
Ces fichiers copiés sont à mettre sur le serveur prepamath.
"""

import os
import re
import shutil
from urllib.parse import urlparse

def find_qrcode_references(tex_files):
    qrcode_pattern = re.compile(r'\\qrcode\{([^}]+)\}')
    references = set()

    for file in tex_files:
        with open(file, 'r', encoding='utf-8') as f:
            content = f.read()
            matches = qrcode_pattern.findall(content)
            for match in matches:
                parsed_url = urlparse(match)
                if parsed_url.netloc == 'idl-live.prepamath.fr':
                    base_name = os.path.basename(parsed_url.path)
                    references.add(base_name)

    return references

import os
import shutil

def copy_files(references, source_dir, dest_dir):
    # Convertir les chemins en chemins absolus
    source_dir = os.path.abspath(source_dir)
    dest_dir = os.path.abspath(dest_dir)

    # Vérifier si le répertoire source existe
    if not os.path.exists(source_dir):
        print(f"Error: Source directory {source_dir} does not exist.")
        return

    # Créer le répertoire de destination s'il n'existe pas
    if not os.path.exists(dest_dir):
        os.makedirs(dest_dir)

    for ref in references:
        base_name, ext = os.path.splitext(ref)
        source_file = f"{base_name}{ext}"
        zip_file = f"{base_name}.zip"

        source_path = os.path.join(source_dir, source_file)
        zip_path = os.path.join(source_dir, zip_file)
        dest_source_path = os.path.join(dest_dir, source_file)
        dest_zip_path = os.path.join(dest_dir, zip_file)

        if os.path.exists(source_path):
            shutil.copy2(source_path, dest_source_path)
            print(f"Copied {source_path} to {dest_source_path}")
        else:
            print(f"Warning: {source_path} does not exist.")

        if os.path.exists(zip_path):
            shutil.copy2(zip_path, dest_zip_path)
            print(f"Copied {zip_path} to {dest_zip_path}")
        else:
            print(f"Warning: {zip_path} does not exist.")


def main():
    tex_dir = 'src/'
    scripts_dir = 'src/scripts/'
    dest_dir = 'src/scripts/serveur/'

    tex_files = [os.path.join(tex_dir, f) for f in os.listdir(tex_dir) if f.endswith('.tex')]
    references = find_qrcode_references(tex_files)
    copy_files(references, scripts_dir, dest_dir)

if __name__ == "__main__":
    main()
