import os
import shutil

from frappe.utils import get_bench_path


def setup_locale():
    bench_path = get_bench_path()
    locale_dir = os.path.join(bench_path, "apps", "az_locale", "az_locale", "locale")

    copied = 0
    skipped = 0

    for entry in sorted(os.listdir(locale_dir)):
        if not entry.startswith("translations_") or not os.path.isdir(os.path.join(locale_dir, entry)):
            continue

        lang = entry.replace("translations_", "", 1)
        lang_dir = os.path.join(locale_dir, entry)

        for app_name in sorted(os.listdir(lang_dir)):
            app_dir = os.path.join(lang_dir, app_name)
            if not os.path.isdir(app_dir):
                continue

            source_file = os.path.join(app_dir, f"{lang}.po")
            if not os.path.exists(source_file):
                print(f"[az_locale] Warning: {source_file} not found, skipping")
                skipped += 1
                continue

            dest_dir = os.path.join(bench_path, "apps", app_name, app_name, "locale")
            if not os.path.isdir(dest_dir):
                print(f"[az_locale] Skipping {app_name}/{lang}.po: app not installed")
                skipped += 1
                continue

            dest_file = os.path.join(dest_dir, f"{lang}.po")
            try:
                shutil.copy2(source_file, dest_file)
                print(f"[az_locale] Copied {lang}.po -> {app_name}")
                copied += 1
            except Exception as e:
                print(f"[az_locale] Error copying to {dest_file}: {e}")
                skipped += 1

    print(f"[az_locale] Locale setup complete: {copied} file(s) copied, {skipped} skipped")
