# -*- coding: utf-8 -*-
import os
import difflib
import chardet
import shutil
import urllib.parse

def normalize_line(line):
    return line.strip()

def detect_encoding(file_path):
    with open(file_path, "rb") as f:
        raw_data = f.read()
        result = chardet.detect(raw_data)
        return result['encoding'] if result['encoding'] else 'utf-8'

def convert_to_utf8(file_path):
    # Erkenne das aktuelle Encoding
    encoding = detect_encoding(file_path)
    if encoding.lower() == 'utf-8':
        return file_path  # Keine Konvertierung notwendig

    # Konvertiere die Datei nach UTF-8
    utf8_path = file_path + ".utf8"
    with open(file_path, "rb") as f:
        content = f.read().decode(encoding, errors="replace")
    with open(utf8_path, "w", encoding="utf-8") as f:
        f.write(content)

    # Originaldatei löschen und umbenennen
    print(f"Konvertiert: {file_path} ({encoding}) -> {utf8_path}")
    os.remove(file_path)
    shutil.move(utf8_path, file_path)

    return file_path

def find_translated_files(original_folder, modified_folder, output_file):
    original_files = {f for f in os.listdir(original_folder) if f.endswith(".js")}
    modified_files = {f for f in os.listdir(modified_folder) if f.endswith(".js")}

    common_files = original_files.intersection(modified_files)
    translated_files = []
    total_differences = 0

    with open(output_file, "w", encoding="utf-8") as f:
        for file_name in sorted(common_files):
            original_path = os.path.abspath(os.path.join(original_folder, file_name))
            modified_path = os.path.abspath(os.path.join(modified_folder, file_name))

            # Dateien in UTF-8 konvertieren, falls notwendig
            original_utf8 = convert_to_utf8(original_path)
            modified_utf8 = convert_to_utf8(modified_path)

            try:
                with open(original_utf8, "r", encoding="utf-8") as orig_file, \
                     open(modified_utf8, "r", encoding="utf-8") as mod_file:

                    original_lines = [normalize_line(line) for line in orig_file if normalize_line(line)]
                    modified_lines = [normalize_line(line) for line in mod_file if normalize_line(line)]
                    
                    diff = list(difflib.unified_diff(original_lines, modified_lines, 
                                                     fromfile=original_path, 
                                                     tofile=modified_path, 
                                                     lineterm=""))

                    if diff:
                        num_changes = sum(1 for line in diff if line.startswith(("-", "+")) and not line.startswith(("---", "+++")))
                        translated_files.append((file_name, num_changes, original_path, modified_path))
                        total_differences += num_changes
                        
                        # VS Code Diff Link erzeugen (absoluter Pfad, URL-enkodiert)
                        encoded_orig = urllib.parse.quote(original_path)
                        encoded_mod = urllib.parse.quote(modified_path)
                        vscode_diff_link = f"vscode://file/{encoded_orig}:0?diff={encoded_mod}:0"
                        
                        # Header und Unterschiede in die Ausgabedatei schreiben
                        f.write(f"📝 Unterschiede in [{file_name}]({vscode_diff_link}) ({num_changes} Änderungen):\n")
                        f.write("\n".join(diff) + "\n\n")

            except Exception as e:
                print(f"Fehler beim Verarbeiten von {file_name}: {e}")

        # Zusammenfassung am Ende der Datei hinzufügen (sortiert)
        f.write("\n🔎 Zusammenfassung der Unterschiede (nach Anzahl der Änderungen sortiert):\n")
        for file_name, count, orig_path, mod_path in sorted(translated_files, key=lambda x: x[1], reverse=True):
            encoded_orig = urllib.parse.quote(orig_path)
            encoded_mod = urllib.parse.quote(mod_path)
            vscode_diff_link = f"vscode://file/{encoded_orig}:0?diff={encoded_mod}:0"
            f.write(f"- [{file_name}]({vscode_diff_link}): {count} Änderungen\n")
        f.write(f"\n📊 Gesamtanzahl der Änderungen: {total_differences}\n")

    print(f"Prüfung abgeschlossen. {len(translated_files)} übersetzte Dateien gefunden.")
    print(f"Ergebnis gespeichert in: {output_file}")

# Beispielpfade (kannst du anpassen)
original_folder = "original_scripts"
modified_folder = "modified_scripts"
output_file = "scripts_with_translation.md"

find_translated_files(original_folder, modified_folder, output_file)
