#!/usr/bin/env python3
"""
Adds the 'offices' translation block to all non-English locale site.php files.
Each file uses array_replace_recursive() ending with:
    ],
    ]
);
We insert the offices block before the final `    ]` + `)`.
"""

import os
import re

BASE = "/mnt/c/Gitrepo/fusionpointai/fusionpointai-laravel/lang"

TRANSLATIONS = {
    "fr": {
        "page_title":       "Bureaux Mondiaux",
        "meta_description": "FusionPointAI exploite plus de 70 bureaux dans plus de 50 pays, avec plus de 12 500 professionnels livrant des solutions d'IA dans le monde entier.",
        "meta_keywords":    "FusionPointAI bureaux, bureaux mondiaux, emplacements, présence internationale",
        "page_intro":       "Un réseau mondial de 70+ bureaux, 12 500+ professionnels et 5 régions — livrant des solutions d'IA d'entreprise à tous les grands marchés.",
        "stats_employees":  "Professionnels Mondiaux",
        "stats_offices":    "Bureaux dans le Monde",
        "stats_countries":  "Pays",
        "stats_regions":    "Régions",
        "map_title":        "Notre Empreinte Mondiale",
        "map_subtitle":     "Cliquez sur un marqueur pour voir les détails du bureau, l'adresse et les liens de carte.",
        "map_note":         "Carte propulsée par OpenStreetMap & Leaflet.js",
        "offices_title":    "Tous les Bureaux",
        "offices_subtitle": "Parcourez nos bureaux par région. Chaque bureau est doté de spécialistes IA certifiés.",
        "offices_label":    "bureaux",
        "hq_badge":         "Siège Mondial",
        "view_google_maps": "Google Maps",
        "view_osm":         "OpenStreetMap",
        "region_all":                "Toutes les Régions",
        "region_europe":             "Europe",
        "region_north_america":      "Amérique du Nord",
        "region_asia_pacific":       "Asie-Pacifique",
        "region_middle_east_africa": "Moyen-Orient & Afrique",
        "region_latin_america":      "Amérique Latine",
    },
    "de": {
        "page_title":       "Globale Büros",
        "meta_description": "FusionPointAI betreibt über 70 Büros in mehr als 50 Ländern mit 12.500+ Fachleuten, die weltweit KI-Lösungen liefern.",
        "meta_keywords":    "FusionPointAI Büros, globale Büros, Standorte, internationale Präsenz",
        "page_intro":       "Ein weltweites Netzwerk von 70+ Büros, 12.500+ Fachleuten und 5 Regionen — KI-Lösungen für alle wichtigen Märkte.",
        "stats_employees":  "Globale Fachleute",
        "stats_offices":    "Büros weltweit",
        "stats_countries":  "Länder",
        "stats_regions":    "Regionen",
        "map_title":        "Unser Globaler Fußabdruck",
        "map_subtitle":     "Klicken Sie auf einen Marker, um Bürodetails, Adresse und Kartenlinks anzuzeigen.",
        "map_note":         "Karte betrieben von OpenStreetMap & Leaflet.js",
        "offices_title":    "Alle Büros",
        "offices_subtitle": "Durchsuchen Sie unsere Büros nach Region. Jedes Büro ist mit zertifizierten KI-Spezialisten besetzt.",
        "offices_label":    "Büros",
        "hq_badge":         "Globaler Hauptsitz",
        "view_google_maps": "Google Maps",
        "view_osm":         "OpenStreetMap",
        "region_all":                "Alle Regionen",
        "region_europe":             "Europa",
        "region_north_america":      "Nordamerika",
        "region_asia_pacific":       "Asien-Pazifik",
        "region_middle_east_africa": "Naher Osten & Afrika",
        "region_latin_america":      "Lateinamerika",
    },
    "es": {
        "page_title":       "Oficinas Globales",
        "meta_description": "FusionPointAI opera más de 70 oficinas en más de 50 países, con 12.500+ profesionales entregando soluciones de IA en todo el mundo.",
        "meta_keywords":    "FusionPointAI oficinas, oficinas globales, ubicaciones, presencia internacional",
        "page_intro":       "Una red mundial de 70+ oficinas, 12.500+ profesionales y 5 regiones — entregando soluciones de IA empresarial a todos los mercados principales.",
        "stats_employees":  "Profesionales Globales",
        "stats_offices":    "Oficinas en el Mundo",
        "stats_countries":  "Países",
        "stats_regions":    "Regiones",
        "map_title":        "Nuestra Huella Global",
        "map_subtitle":     "Haga clic en cualquier marcador para ver detalles de la oficina, dirección y enlaces al mapa.",
        "map_note":         "Mapa impulsado por OpenStreetMap y Leaflet.js",
        "offices_title":    "Todas las Oficinas",
        "offices_subtitle": "Explore nuestras oficinas por región. Cada oficina cuenta con especialistas en IA certificados.",
        "offices_label":    "oficinas",
        "hq_badge":         "Sede Global",
        "view_google_maps": "Google Maps",
        "view_osm":         "OpenStreetMap",
        "region_all":                "Todas las Regiones",
        "region_europe":             "Europa",
        "region_north_america":      "América del Norte",
        "region_asia_pacific":       "Asia-Pacífico",
        "region_middle_east_africa": "Oriente Medio y África",
        "region_latin_america":      "América Latina",
    },
    "pt": {
        "page_title":       "Escritórios Globais",
        "meta_description": "A FusionPointAI opera mais de 70 escritórios em mais de 50 países, com 12.500+ profissionais entregando soluções de IA em todo o mundo.",
        "meta_keywords":    "FusionPointAI escritórios, escritórios globais, localizações, presença internacional",
        "page_intro":       "Uma rede mundial de 70+ escritórios, 12.500+ profissionais e 5 regiões — entregando soluções de IA empresarial a todos os principais mercados.",
        "stats_employees":  "Profissionais Globais",
        "stats_offices":    "Escritórios no Mundo",
        "stats_countries":  "Países",
        "stats_regions":    "Regiões",
        "map_title":        "Nossa Presença Global",
        "map_subtitle":     "Clique em qualquer marcador para ver detalhes do escritório, endereço e links do mapa.",
        "map_note":         "Mapa fornecido por OpenStreetMap e Leaflet.js",
        "offices_title":    "Todos os Escritórios",
        "offices_subtitle": "Navegue pelos nossos escritórios por região. Cada escritório conta com especialistas em IA certificados.",
        "offices_label":    "escritórios",
        "hq_badge":         "Sede Global",
        "view_google_maps": "Google Maps",
        "view_osm":         "OpenStreetMap",
        "region_all":                "Todas as Regiões",
        "region_europe":             "Europa",
        "region_north_america":      "América do Norte",
        "region_asia_pacific":       "Ásia-Pacífico",
        "region_middle_east_africa": "Oriente Médio e África",
        "region_latin_america":      "América Latina",
    },
    "ru": {
        "page_title":       "Глобальные Офисы",
        "meta_description": "FusionPointAI управляет более чем 70 офисами в 50+ странах с 12 500+ специалистами, предоставляющими решения ИИ по всему миру.",
        "meta_keywords":    "FusionPointAI офисы, глобальные офисы, местоположения, международное присутствие",
        "page_intro":       "Всемирная сеть из 70+ офисов, 12 500+ специалистов и 5 регионов — корпоративные решения ИИ для всех крупных рынков.",
        "stats_employees":  "Глобальных Специалистов",
        "stats_offices":    "Офисов по Миру",
        "stats_countries":  "Стран",
        "stats_regions":    "Регионов",
        "map_title":        "Наше Глобальное Присутствие",
        "map_subtitle":     "Нажмите на маркер, чтобы просмотреть данные офиса, адрес и ссылки на карту.",
        "map_note":         "Карта на основе OpenStreetMap и Leaflet.js",
        "offices_title":    "Все Офисы",
        "offices_subtitle": "Просматривайте наши офисы по регионам. В каждом офисе работают сертифицированные специалисты по ИИ.",
        "offices_label":    "офисов",
        "hq_badge":         "Главный Офис",
        "view_google_maps": "Google Карты",
        "view_osm":         "OpenStreetMap",
        "region_all":                "Все Регионы",
        "region_europe":             "Европа",
        "region_north_america":      "Северная Америка",
        "region_asia_pacific":       "Азиатско-Тихоокеанский",
        "region_middle_east_africa": "Ближний Восток и Африка",
        "region_latin_america":      "Латинская Америка",
    },
    "zh": {
        "page_title":       "全球办公室",
        "meta_description": "FusionPointAI在50多个国家拥有70多个办公室，12,500多名专业人员在全球提供AI解决方案。",
        "meta_keywords":    "FusionPointAI办公室, 全球办公室, 地点, 国际影响力",
        "page_intro":       "遍布全球的70多个办公室、12,500多名专业人员和5个地区网络——为所有主要市场提供企业AI解决方案。",
        "stats_employees":  "全球专业人员",
        "stats_offices":    "全球办公室",
        "stats_countries":  "国家",
        "stats_regions":    "地区",
        "map_title":        "我们的全球布局",
        "map_subtitle":     "点击任意标记可查看办公室详细信息、地址和地图链接。",
        "map_note":         "地图由OpenStreetMap和Leaflet.js提供支持",
        "offices_title":    "所有办公室",
        "offices_subtitle": "按地区浏览我们的办公室。每个办公室都配备了认证的AI专家。",
        "offices_label":    "个办公室",
        "hq_badge":         "全球总部",
        "view_google_maps": "谷歌地图",
        "view_osm":         "OpenStreetMap",
        "region_all":                "所有地区",
        "region_europe":             "欧洲",
        "region_north_america":      "北美洲",
        "region_asia_pacific":       "亚太地区",
        "region_middle_east_africa": "中东与非洲",
        "region_latin_america":      "拉丁美洲",
    },
    "ja": {
        "page_title":       "グローバルオフィス",
        "meta_description": "FusionPointAIは50カ国以上に70以上のオフィスを運営し、12,500人以上の専門家が世界中でAIソリューションを提供しています。",
        "meta_keywords":    "FusionPointAIオフィス, グローバルオフィス, 所在地, 国際展開",
        "page_intro":       "70以上のオフィス、12,500人以上の専門家、5つの地域からなるグローバルネットワーク — 主要市場すべてにエンタープライズAIソリューションを提供。",
        "stats_employees":  "グローバル専門家",
        "stats_offices":    "世界のオフィス",
        "stats_countries":  "カ国",
        "stats_regions":    "地域",
        "map_title":        "グローバルな展開",
        "map_subtitle":     "マーカーをクリックすると、オフィスの詳細、住所、地図リンクが表示されます。",
        "map_note":         "地図はOpenStreetMapとLeaflet.jsを使用しています",
        "offices_title":    "全オフィス",
        "offices_subtitle": "地域別にオフィスを閲覧できます。すべてのオフィスに認定AI専門家が在籍しています。",
        "offices_label":    "オフィス",
        "hq_badge":         "グローバル本社",
        "view_google_maps": "Googleマップ",
        "view_osm":         "OpenStreetMap",
        "region_all":                "全地域",
        "region_europe":             "ヨーロッパ",
        "region_north_america":      "北アメリカ",
        "region_asia_pacific":       "アジア太平洋",
        "region_middle_east_africa": "中東・アフリカ",
        "region_latin_america":      "ラテンアメリカ",
    },
    "hi": {
        "page_title":       "वैश्विक कार्यालय",
        "meta_description": "FusionPointAI 50+ देशों में 70+ कार्यालयों का संचालन करता है, जिसमें 12,500+ पेशेवर विश्वभर में AI समाधान प्रदान करते हैं।",
        "meta_keywords":    "FusionPointAI कार्यालय, वैश्विक कार्यालय, स्थान, अंतर्राष्ट्रीय उपस्थिति",
        "page_intro":       "70+ कार्यालयों, 12,500+ पेशेवरों और 5 क्षेत्रों का एक वैश्विक नेटवर्क — सभी प्रमुख बाजारों को एंटरप्राइज़ AI समाधान प्रदान करता है।",
        "stats_employees":  "वैश्विक पेशेवर",
        "stats_offices":    "विश्वभर के कार्यालय",
        "stats_countries":  "देश",
        "stats_regions":    "क्षेत्र",
        "map_title":        "हमारी वैश्विक उपस्थिति",
        "map_subtitle":     "कार्यालय विवरण, पता और मानचित्र लिंक देखने के लिए किसी भी मार्कर पर क्लिक करें।",
        "map_note":         "मानचित्र OpenStreetMap और Leaflet.js द्वारा संचालित",
        "offices_title":    "सभी कार्यालय",
        "offices_subtitle": "क्षेत्र के अनुसार हमारे कार्यालय ब्राउज़ करें। प्रत्येक कार्यालय में प्रमाणित AI विशेषज्ञ हैं।",
        "offices_label":    "कार्यालय",
        "hq_badge":         "वैश्विक मुख्यालय",
        "view_google_maps": "Google Maps",
        "view_osm":         "OpenStreetMap",
        "region_all":                "सभी क्षेत्र",
        "region_europe":             "यूरोप",
        "region_north_america":      "उत्तरी अमेरिका",
        "region_asia_pacific":       "एशिया-प्रशांत",
        "region_middle_east_africa": "मध्य पूर्व और अफ्रीका",
        "region_latin_america":      "लैटिन अमेरिका",
    },
    "ar": {
        "page_title":       "المكاتب العالمية",
        "meta_description": "تدير FusionPointAI أكثر من 70 مكتبًا في أكثر من 50 دولة، مع أكثر من 12,500 متخصص يقدمون حلول الذكاء الاصطناعي حول العالم.",
        "meta_keywords":    "مكاتب FusionPointAI, مكاتب عالمية, مواقع, حضور دولي",
        "page_intro":       "شبكة عالمية تضم أكثر من 70 مكتبًا، وأكثر من 12,500 متخصص، و5 مناطق — تقديم حلول الذكاء الاصطناعي للمؤسسات في جميع الأسواق الرئيسية.",
        "stats_employees":  "متخصص عالمي",
        "stats_offices":    "مكتب حول العالم",
        "stats_countries":  "دولة",
        "stats_regions":    "منطقة",
        "map_title":        "بصمتنا العالمية",
        "map_subtitle":     "انقر على أي علامة لعرض تفاصيل المكتب والعنوان وروابط الخريطة.",
        "map_note":         "الخريطة مدعومة من OpenStreetMap و Leaflet.js",
        "offices_title":    "جميع المكاتب",
        "offices_subtitle": "تصفح مكاتبنا حسب المنطقة. كل مكتب مزود بمتخصصين معتمدين في الذكاء الاصطناعي.",
        "offices_label":    "مكتب",
        "hq_badge":         "المقر الرئيسي العالمي",
        "view_google_maps": "خرائط Google",
        "view_osm":         "OpenStreetMap",
        "region_all":                "جميع المناطق",
        "region_europe":             "أوروبا",
        "region_north_america":      "أمريكا الشمالية",
        "region_asia_pacific":       "آسيا والمحيط الهادئ",
        "region_middle_east_africa": "الشرق الأوسط وأفريقيا",
        "region_latin_america":      "أمريكا اللاتينية",
    },
}

def build_offices_block(t):
    lines = [
        "    'offices' => [",
        f"        'page_title'        => '{t['page_title']}',",
        f"        'meta_description'  => '{t['meta_description']}',",
        f"        'meta_keywords'     => '{t['meta_keywords']}',",
        f"        'page_intro'        => '{t['page_intro']}',",
        f"        'stats_employees'   => '{t['stats_employees']}',",
        f"        'stats_offices'     => '{t['stats_offices']}',",
        f"        'stats_countries'   => '{t['stats_countries']}',",
        f"        'stats_regions'     => '{t['stats_regions']}',",
        f"        'map_title'         => '{t['map_title']}',",
        f"        'map_subtitle'      => '{t['map_subtitle']}',",
        f"        'map_note'          => '{t['map_note']}',",
        f"        'offices_title'     => '{t['offices_title']}',",
        f"        'offices_subtitle'  => '{t['offices_subtitle']}',",
        f"        'offices_label'     => '{t['offices_label']}',",
        f"        'hq_badge'          => '{t['hq_badge']}',",
        f"        'view_google_maps'  => '{t['view_google_maps']}',",
        f"        'view_osm'          => '{t['view_osm']}',",
        f"        'region_all'                => '{t['region_all']}',",
        f"        'region_europe'             => '{t['region_europe']}',",
        f"        'region_north_america'      => '{t['region_north_america']}',",
        f"        'region_asia_pacific'       => '{t['region_asia_pacific']}',",
        f"        'region_middle_east_africa' => '{t['region_middle_east_africa']}',",
        f"        'region_latin_america'      => '{t['region_latin_america']}',",
        "    ],",
    ]
    return "\n".join(lines)

for locale, t in TRANSLATIONS.items():
    filepath = os.path.join(BASE, locale, "site.php")
    if not os.path.exists(filepath):
        print(f"SKIP: {filepath} not found")
        continue

    with open(filepath, "r", encoding="utf-8") as f:
        content = f.read()

    # Skip if already added
    if "'offices'" in content:
        print(f"SKIP: {locale} already has offices key")
        continue

    # The file ends with:  "\n    ]\n);\n" (possibly with trailing newline)
    # We insert the offices block before the final "    ]"
    offices_block = build_offices_block(t)

    # Match the last occurrence of "\n    ]\n);"
    old_ending = "\n    ]\n);"
    new_ending = "\n" + offices_block + "\n    ]\n);"

    if old_ending not in content:
        print(f"ERROR: Could not find ending pattern in {locale}/site.php")
        continue

    # Replace last occurrence only
    idx = content.rfind(old_ending)
    new_content = content[:idx] + new_ending + content[idx + len(old_ending):]

    with open(filepath, "w", encoding="utf-8") as f:
        f.write(new_content)

    print(f"OK: {locale}/site.php updated")

print("Done.")
