"""
Internationalization module.
Supports Slovak (sk) and English (en).
"""

TRANSLATIONS = {
    "sk": {
        # App / Sidebar
        "app_title": "LLM Verifier",
        "nav_label": "Navigácia",
        "nav_testing": "Nové testovanie",
        "nav_data": "Správa modelov a dát",
        "nav_history": "História a Štatistiky",
        "language_label": "Jazyk / Language",

        # Data Management
        "data_header": "Správa modelov a vstupných dát",
        "data_tab_inputs": "Vstupné dokumenty",
        "data_tab_models": "Matematické modely",
        "data_tab_llm_caps": "Schopnosti LLM modelov",
        "data_input_subheader": "Vstupné dokumenty",
        "data_add_input_group": "Pridať novú skupinu vstupov",
        "data_input_folder_name": "Názov priečinka pre vstupy (napr. 'TLR_Experiment'):",
        "data_upload_files": "Nahrať súbory",
        "data_save_inputs": "Uložiť skupinu vstupov",
        "data_inputs_saved": "Vstupy pre '{name}' úspešne uložené!",
        "data_input_warning": "Zadajte názov priečinka a nahrajte aspoň jeden súbor.",
        "data_available_inputs": "Dostupné vstupy (Priečinky):",
        "data_no_inputs": "Zatiaľ žiadne nahraté vstupy.",
        "data_models_subheader": "Matematické modely",
        "data_add_model": "Pridať nový model",
        "data_model_folder_name": "Názov priečinka modelu (napr. 'id-061'):",
        "data_upload_model_files": "Nahrať súbory pre tento model",
        "data_save_models": "Uložiť skupinu modelov",
        "data_models_saved": "Model '{name}' úspešne uložený!",
        "data_model_warning": "Zadajte názov modelu a nahrajte aspoň jeden súbor.",
        "data_available_models": "Dostupné modely (Priečinky):",
        "data_no_models": "Zatiaľ žiadne nahraté modely.",

        # LLM Capabilities
        "data_llm_caps_header": "Schopnosti LLM modelov",
        "data_llm_caps_help": "Nastavte, ako má extraktor pracovať so súbormi pre každý model. 'Auto' použije vstavané rozpoznávanie podľa názvu modelu.",
        "data_llm_caps_no_models": "Najprv načítajte zoznam modelov (skontrolujte API token).",
        "data_llm_col_model": "Model",
        "data_llm_col_vision": "Obrázky",
        "data_llm_col_pdf_auto": "PDF (auto)",
        "data_llm_col_pdf_override": "PDF — nastavenie",
        "data_llm_pdf_auto": "Auto (podľa registra)",
        "data_llm_pdf_extract": "Vždy extrahovať text",
        "data_llm_pdf_native": "Odoslať ako PDF",
        "data_llm_caps_save": "Uložiť nastavenia",
        "data_llm_caps_saved": "Nastavenia schopností modelov boli uložené.",

        # Testing
        "testing_header": "Spustenie Benchmarku",
        "testing_no_data_warning": "Pre spustenie testu musíte najprv nahrať aspoň jednu skupinu vstupov a jednu skupinu modelov.",
        "testing_tab_single": "Jednotlivý test (Single Run)",
        "testing_tab_batch": "Hromadný test (Batch Run)",
        "testing_data_pairing": "1. Párovanie dát",
        "testing_select_input": "Vyberte vstupný dataset:",
        "testing_select_model": "Vyberte referenčný model:",
        "testing_llm_setup": "2. Nastavenie LLM",
        "testing_select_llm": "Vyberte LLM model:",
        "testing_prompt_section": "3. Úprava systémového promptu",
        "testing_prompt_label": "System Prompt:",
        "testing_save_prompt": "Uložiť text ako nový predvolený prompt",
        "testing_prompt_saved": "Predvolený prompt uložený!",
        "testing_run_btn": "Spustiť extrakciu a verifikáciu",
        "testing_spinner": "Analyzujem a verifikujem (Model: {llm})...",
        "testing_error": "Nastala chyba: {error}",
        "testing_success": "Testovanie úspešné!",
        "testing_results_subheader": "Výsledky verifikácie",
        "testing_verified": "VERIFIED",
        "testing_not_verified": "NOT VERIFIED",
        "testing_unknown_phenotype": "Neznámy fenotyp",
        "testing_batch_info": "Hromadný test umožňuje spárovať konkrétne vstupy s konkrétnymi modelmi a prehnať ich cez viaceré LLM.",
        "testing_batch_select_llms": "1. Vyberte LLM modely na porovnanie",
        "testing_batch_select_llm_label": "Vyberte LLM:",
        "testing_batch_map": "2. Namapujte Vstupy na AEON Modely",
        "testing_batch_input_label": "Vstup {n}:",
        "testing_batch_model_label": "Model {n}:",
        "testing_batch_add_pair": "Pridať ďalší pár na otestovanie",
        "testing_batch_prompt_section": "3. Úprava systémového promptu",
        "testing_batch_prompt_label": "System Prompt (spoločný pre všetky behy v tejto dávke):",
        "testing_batch_total_runs": "**Celkový počet plánovaných behov:** {total} (Páry: {pairs} × LLM modely: {llms})",
        "testing_batch_run_btn": "Spustiť Namapovaný Benchmark",
        "testing_batch_log_header": "Priebeh testovania (Log):",
        "testing_batch_progress": "**Beh {done}/{total}:** LLM: `{llm}` | Pár: `{inp}` → `{mod}`...",
        "testing_batch_run_success": "Beh {n}: `{llm}` spracoval `{inp}` → Úspešné (Uložené v Histórii)",
        "testing_batch_run_error": "Beh {n}: `{llm}` spracoval `{inp}` → Zlyhalo ({error})",
        "testing_batch_critical_error": "Kritická chyba v Behu {n}: {error}",
        "testing_batch_done": "**Hromadný benchmark dokončený!**",
        "testing_batch_success_summary": "**Úspešné behy:** {success} / {total}",
        "testing_error_no_model_files": "Vybraný model neobsahuje .bnet alebo .aeon súbor!",
        "testing_error_extraction_failed": "Extrakcia zlyhala (LLM nevrátilo validný JSON).",
        "testing_milestone_label": "Míľnik:",
        "testing_milestone_help": "Priradí tento beh k danému míľniku pre potreby histórie a porovnania.",
        "testing_use_model_context_label": "Pridať kontext modelu do promptu",
        "testing_use_model_context_help": "Ak je zapnuté, názvy premenných z matematického modelu sa pridajú do promptu, aby LLM lepšie rozpoznalo premenné.",

        # Background jobs
        "testing_bg_jobs_header": "Behy na pozadí",
        "testing_bg_jobs_none": "Žiadne behy na pozadí.",
        "testing_bg_jobs_cancel": "Zrušiť",
        "testing_bg_jobs_cancel_group": "Zrušiť skupinu",
        "testing_bg_jobs_clear": "Vymazať dokončené",
        "testing_bg_status_pending":   ":material/hourglass_empty: Čaká",
        "testing_bg_status_running":   ":material/sync: Beží...",
        "testing_bg_status_done":      ":material/check_circle: Hotovo",
        "testing_bg_status_failed":    ":material/cancel: Zlyhalo",
        "testing_bg_status_cancelled": ":material/block: Zrušené",
        "testing_repetitions_label": "Počet opakovaní:",
        "testing_repetitions_help": "Každú konfiguráciu spustí toľkokrát. Slúži na overenie konzistentnosti výstupu.",
        "testing_submitted_bg": "{n} beh(y) odoslaných na pozadie. Môžete prechádzať na iné stránky.",
        "testing_bg_job_rep": "Opakovanie {rep}/{total}",
        "testing_batch_total_with_reps": "**Celkový počet plánovaných behov:** {total} (Páry: {pairs} × LLM: {llms} × Opakovania: {reps})",

        # History
        "history_header": "História behov a Štatistiky",
        "history_no_runs": "Zatiaľ neboli vykonané žiadne testy.",
        "history_overview": "Celkový prehľad",
        "history_total_runs": "Celkový počet behov",
        "history_extracted": "Extrahované fenotypy",
        "history_verified_total": "Úspešne verifikované",
        "history_success_rate": "Verifikačná Úspešnosť",
        "history_coverage": "Pokrytie Modelu",
        "history_coverage_help": "Pomer medzi fenotypmi, ktoré extrahovalo LLM a celkovým počtom atraktorov, ktoré umožňuje matematický model.",
        "history_coverage_na_help": "Pre výpočet spustite nové testy s novou verziou verifikátora.",
        "history_tab_stats": "Štatistiky a Grafy",
        "history_tab_failures": "Analýza Chýb",
        "history_tab_details": "Detailné Behy",
        "history_chart_success_by_llm": "Úspešnosť Verifikácie podľa LLM",
        "history_chart_coverage_by_llm": "Pokrytie Modelu podľa LLM",
        "history_chart_no_coverage": "Nie sú dostupné dáta pre graf pokrytia.",
        "history_chart_success_pct": "Úspešnosť (%)",
        "history_chart_coverage_pct": "Pokrytie (%)",
        "history_table_header": "Detailná tabuľka všetkých behov",
        "history_export_csv": "Stiahnuť tabuľku ako CSV",
        "history_failures_header": "Prehľad neúspešných extrakcií (NOT VERIFIED)",
        "history_failures_info": "Tu sú zoskupené všetky fenotypy, ktoré sa podarilo vyextrahovať, ale matematický model ich nepotvrdil. Slúži to na identifikáciu halucinácií alebo zlého promptingu.",
        "history_no_failures": "Skvelé správy! Zatiaľ neevidujeme žiadne zlyhané fenotypy.",
        "history_filter_llm": "Filtrovať podľa LLM modelu:",
        "history_filter_all": "Všetky",
        "history_failures_rationale": "Detailný výpis Dôvodov (Rationale)",
        "history_failure_variables": "**Navrhované premenné a stavy:**",
        "history_failure_rationale_label": "**Zdôvodenie modelu (Prečo si myslel, že to má byť takto):**",
        "history_source_run": "Zdrojový beh: {file}",
        "history_details_header": "Zobrazenie surových JSON výsledkov",
        "history_details_select_run": "Vyberte súbor na prezeranie detailov:",
        "history_details_prompt_label": "**Použitý prompt:**",
        "history_details_results_label": "**Výsledky:**",
        "history_details_error_msg": "Tento beh zlyhal a neobsahuje fenotypy. Namiesto toho LLM vrátilo túto chybu:",
        "history_details_nonstandard": "Neštandardný výstup: {item}",
        "history_tokens_prompt": "Request tokeny",
        "history_tokens_response": "Response tokeny",
        "history_tokens_total": "Celkové tokeny",
        "history_read_error": "Chyba pri čítaní {file}: {error}",
        "history_col_datetime": "Dátum a Čas",
        "history_col_llm": "Model (LLM)",
        "history_col_input": "Vstup (Dáta)",
        "history_col_aeon": "AEON Model",
        "history_col_attractors": "Atraktory v Modeli",
        "history_col_phenotypes": "Extrahované Fenotypy",
        "history_col_verified": "Verifikované",
        "history_col_success_rate": "Úspešnosť Verifikácie (%)",
        "history_col_coverage": "Pokrytie Modelu (%)",
        "history_col_file": "Súbor",
        "history_col_tokens": "Použité tokeny",
        "history_col_milestone": "Míľnik",
        "history_milestone_label": "Zobraziť míľnik:",
        "history_milestone_all": "Všetky",
        "history_milestone_prefix": "Míľnik",
        "history_col_run_count": "Počet behov",
        "history_col_correct_runs": "Správnych",
        "history_col_incorrect_runs": "Nesprávnych",
        "history_col_avg_tokens": "Priemer tokenov",
        "history_correct_runs_metric": "Správnych behov",
        "history_incorrect_runs_metric": "Nesprávnych behov",
        "history_rebuild_index_label": "Správa indexu behov",
        "history_rebuild_index_help": "Index sa automaticky aktualizuje pri každom novom behu. Ak máte importované staré JSON súbory, použite toto tlačidlo na jeho opätovné vytvorenie.",
        "history_rebuild_index_btn": "Preindexovať všetky behy",
        "history_rebuild_index_spinner": "Indexujem...",
        "history_rebuild_index_done": "Index bol úspešne vytvorený pre {n} behov.",
        "history_refresh_btn": "Obnoviť dáta",
        "history_llm_table_header": "Prehľad LLM modelov",
        "history_llm_table_group_by_model": "Zoskupiť podľa LLM + Model",
        "history_llm_table_group_by_model_help": "Zapnite pre zobrazenie výsledkov rozdelených podľa LLM a testovaného modelu.",
        "history_milestone_summary_header": "Súhrn podľa míľnika",
        "history_milestone_export_csv": "Stiahnuť súhrn míľnikov ako CSV",
        "history_milestone_export_filename": "suhrn_milnikov_{date}.csv",
        "history_fail_col_llm": "LLM Model",
        "history_fail_col_phenotype": "Názov fenotypu",
        "history_fail_col_rationale": "Odôvodnenie (Rationale)",
        "history_fail_col_variables": "Extrahované premenné",
        "history_fail_col_file": "Súbor",
        "history_unknown_llm": "Neznámy",
        "history_unknown_input": "Neznámy",
        "history_unknown_model": "Neznámy",
        "history_unknown_phenotype": "Neznámy",
        "history_no_rationale": "Bez odôvodnenia",

        # Diagnostics tab
        "history_tab_diagnostics": "Diagnostika zlyhaní",
        "history_diag_header": "Interaktívna diagnostika nekonzistencií",
        "history_diag_info": "Tu sú zoskupené fenotypy, ktoré matematický model nepotvrdil. Kategorizujte ich pre potreby diskusie v diplomovej práci. Údaje sa automaticky ukladajú.",
        "history_diag_cat_unclassified": "Nezaradené",
        "history_diag_cat_hallucination": "Logická halucinácia",
        "history_diag_cat_misinterpretation": "Kontextuálna dezinterpretácia",
        "history_diag_cat_discrepancy": "Diskrepancia modelu",
        "history_diag_rationale_label": "**Dôvodenie (Rationale):**",
        "history_diag_extracted_label": "**Extrahované z textu (LLM):**",
        "history_diag_compare_popover": "Porovnať extrakciu voči modelu (Rozdiely)",
        "history_diag_compare_desc": "Detailné porovnanie toho, čo našlo LLM, voči možným stavom v AEON modeli.",
        "history_diag_no_attractor_details": "Pre tento model neboli uložené detaily atraktorov.",
        "history_diag_attractor_tab": "Atraktor #{id}",
        "history_diag_matches": "**Zhodné ({n}):**",
        "history_diag_incorrect": "**Nesprávny stav ({n}):**",
        "history_diag_incorrect_item": "- `{k}`: LLM navrhlo `{got}`, ale model vyžaduje `{expected}`",
        "history_diag_hallucinated": "**Vymyslené premenné ({n}):**",
        "history_diag_hallucinated_item": "- `{k}`: Neexistuje v modeli",
        "history_diag_missing_expander": "Chýbajúce premenné v extrakcii ({n})",
        "history_diag_missing_desc": "Tieto premenné tvoria zvyšok atraktora, ale LLM ich z textu neextrahovalo:",
        "history_diag_compare_error": "Nepodarilo sa načítať porovnanie: {error}",
        "history_diag_stats_header": "Štatistický profil zlyhaní",
        "history_diag_col_category": "Kategória",
        "history_diag_col_count": "Počet",
        "history_diag_no_errors": "Zatiaľ neboli zaznamenané žiadne chyby pre tento výber.",
        "history_diag_progress_label": "**Celkový postup analýzy:**",
        "history_diag_progress_count": "Zaradené: {analyzed} / {total}",
        "history_diag_download_btn": "Stiahnuť diagnostiku (CSV)",
        "history_diag_download_confirm": "Potvrdiť stiahnutie",
        "history_diag_export_col": "Expertná Kategória",
        "history_diag_export_filename": "diagnostika_chyb_{date}.csv",
        "history_diag_classify_label": "Zaradiť chybu:",

        # Optional sections
        "history_show_runs_toggle": "Zobraziť všetky behy ({n})",
        "history_download_runs_csv": "Stiahnuť behy ako CSV",
        "history_show_failures_toggle": "Načítať analýzu zlyhaní",
        "history_failures_hidden_hint": "{n} neverifikovaných fenotypov — zapnite prepínač pre načítanie analýzy",

        # Models
        "models_fetch_error": "Nepodarilo sa načítať modely z e-INFRA API: {error}",
        "models_gemini_fetch_error": "Nepodarilo sa načítať Gemini modely: {error}",

        # Extractor
        "extractor_init_error": "Kritická chyba pri inicializácii modelu {model}: {error}",
        "extractor_dir_missing": "Chyba: Priečinok {path} neexistuje.",
        "extractor_prompt_intro": "Analyzuj nasledujúce podklady (text a obrázky) a extrahuj z nich fenotypy:",
        "extractor_model_context_header": "\n\n--- KONTEXT: VÝPOČTOVÝ MODEL ({name}) ---\nTu sú definované presné názvy premenných (ID), ktoré musíš použiť:\n\n",
        "extractor_model_context_footer": "--------------------------------------------------\nUPOZORNENIE: Nepoužívaj všeobecné názvy (napr. 'NF-kB'), ale nájdi k nim zodpovedajúce ID v zozname vyššie (napr. 'v_NfkB_H').\n",
        "extractor_model_load_error": "Nepodarilo sa načítať model: {error}",
        "extractor_text_section": "\n--- TEXT Z {name} ---\n{text}",
        "extractor_api_error": "Chyba API pri extrakcii (Model: {model}): {error}",

        # Testing (background jobs)
        "testing_cancelled_before_extraction": "Zrušené pred extrakciou.",
        "testing_cancelled_before_verification": "Zrušené pred verifikáciou.",
        "testing_bg_active": ":material/sync: {n} aktívnych",
        "testing_bg_all_done": "Všetky úlohy dokončené",

        # Config
        "config_save_error": "Chyba pri ukladaní {name}: {error}",
    },
    "en": {
        # App / Sidebar
        "app_title": "LLM Verifier",
        "nav_label": "Navigation",
        "nav_testing": "New Test Run",
        "nav_data": "Model & Data Management",
        "nav_history": "History & Statistics",
        "language_label": "Jazyk / Language",

        # Data Management
        "data_header": "Model & Input Data Management",
        "data_tab_inputs": "Input Documents",
        "data_tab_models": "Math Models",
        "data_tab_llm_caps": "LLM Capabilities",
        "data_input_subheader": "Input Documents",
        "data_add_input_group": "Add new input group",
        "data_input_folder_name": "Folder name for inputs (e.g. 'TLR_Experiment'):",
        "data_upload_files": "Upload files",
        "data_save_inputs": "Save input group",
        "data_inputs_saved": "Inputs for '{name}' saved successfully!",
        "data_input_warning": "Please enter a folder name and upload at least one file.",
        "data_available_inputs": "Available inputs (Folders):",
        "data_no_inputs": "No inputs uploaded yet.",
        "data_models_subheader": "Mathematical Models",
        "data_add_model": "Add new model",
        "data_model_folder_name": "Model folder name (e.g. 'id-061'):",
        "data_upload_model_files": "Upload files for this model",
        "data_save_models": "Save model group",
        "data_models_saved": "Model '{name}' saved successfully!",
        "data_model_warning": "Please enter a model name and upload at least one file.",
        "data_available_models": "Available models (Folders):",
        "data_no_models": "No models uploaded yet.",

        # LLM Capabilities
        "data_llm_caps_header": "LLM Model Capabilities",
        "data_llm_caps_help": "Configure how the extractor handles input files for each model. 'Auto' uses built-in name-based detection from the registry.",
        "data_llm_caps_no_models": "Load the model list first (check your API token).",
        "data_llm_col_model": "Model",
        "data_llm_col_vision": "Images",
        "data_llm_col_pdf_auto": "PDF (auto)",
        "data_llm_col_pdf_override": "PDF — override",
        "data_llm_pdf_auto": "Auto (registry)",
        "data_llm_pdf_extract": "Always extract text",
        "data_llm_pdf_native": "Send as native PDF",
        "data_llm_caps_save": "Save settings",
        "data_llm_caps_saved": "Model capability settings saved.",

        # Testing
        "testing_header": "Run Benchmark",
        "testing_no_data_warning": "Please upload at least one input group and one model group before running a test.",
        "testing_tab_single": "Single Run",
        "testing_tab_batch": "Batch Run",
        "testing_data_pairing": "1. Data Pairing",
        "testing_select_input": "Select input dataset:",
        "testing_select_model": "Select reference model:",
        "testing_llm_setup": "2. LLM Configuration",
        "testing_select_llm": "Select LLM model:",
        "testing_prompt_section": "3. System Prompt",
        "testing_prompt_label": "System Prompt:",
        "testing_save_prompt": "Save as new default prompt",
        "testing_prompt_saved": "Default prompt saved!",
        "testing_run_btn": "Run Extraction & Verification",
        "testing_spinner": "Analysing and verifying (Model: {llm})...",
        "testing_error": "An error occurred: {error}",
        "testing_success": "Testing successful!",
        "testing_results_subheader": "Verification Results",
        "testing_verified": "VERIFIED",
        "testing_not_verified": "NOT VERIFIED",
        "testing_unknown_phenotype": "Unknown phenotype",
        "testing_batch_info": "Batch run allows you to pair specific inputs with specific models and run them through multiple LLMs.",
        "testing_batch_select_llms": "1. Select LLM models to compare",
        "testing_batch_select_llm_label": "Select LLMs:",
        "testing_batch_map": "2. Map Inputs to AEON Models",
        "testing_batch_input_label": "Input {n}:",
        "testing_batch_model_label": "Model {n}:",
        "testing_batch_add_pair": "Add another pair",
        "testing_batch_prompt_section": "3. System Prompt",
        "testing_batch_prompt_label": "System Prompt (shared for all runs in this batch):",
        "testing_batch_total_runs": "**Total planned runs:** {total} (Pairs: {pairs} × LLM models: {llms})",
        "testing_batch_run_btn": "Run Mapped Benchmark",
        "testing_batch_log_header": "Test Progress (Log):",
        "testing_batch_progress": "**Run {done}/{total}:** LLM: `{llm}` | Pair: `{inp}` → `{mod}`...",
        "testing_batch_run_success": "Run {n}: `{llm}` processed `{inp}` → Success (Saved to History)",
        "testing_batch_run_error": "Run {n}: `{llm}` processed `{inp}` → Failed ({error})",
        "testing_batch_critical_error": "Critical error in Run {n}: {error}",
        "testing_batch_done": "**Batch benchmark completed!**",
        "testing_batch_success_summary": "**Successful runs:** {success} / {total}",
        "testing_error_no_model_files": "Selected model does not contain a .bnet or .aeon file!",
        "testing_error_extraction_failed": "Extraction failed (LLM did not return valid JSON).",
        "testing_milestone_label": "Milestone:",
        "testing_milestone_help": "Assigns this run to a milestone for history and comparison purposes.",
        "testing_use_model_context_label": "Add model variable context to prompt",
        "testing_use_model_context_help": "When enabled, variable names from the mathematical model are injected into the prompt to help the LLM identify variables correctly.",

        # Background jobs
        "testing_bg_jobs_header": "Background Jobs",
        "testing_bg_jobs_none": "No background jobs running.",
        "testing_bg_jobs_cancel": "Cancel",
        "testing_bg_jobs_cancel_group": "Cancel group",
        "testing_bg_jobs_clear": "Clear finished",
        "testing_bg_status_pending":   ":material/hourglass_empty: Pending",
        "testing_bg_status_running":   ":material/sync: Running...",
        "testing_bg_status_done":      ":material/check_circle: Done",
        "testing_bg_status_failed":    ":material/cancel: Failed",
        "testing_bg_status_cancelled": ":material/block: Cancelled",
        "testing_repetitions_label": "Repetitions:",
        "testing_repetitions_help": "Run each configuration this many times to confirm result consistency.",
        "testing_submitted_bg": "{n} run(s) submitted to background. You can freely navigate to other pages.",
        "testing_bg_job_rep": "Repetition {rep}/{total}",
        "testing_batch_total_with_reps": "**Total planned runs:** {total} (Pairs: {pairs} × LLMs: {llms} × Repetitions: {reps})",

        # History
        "history_header": "Run History & Statistics",
        "history_no_runs": "No tests have been run yet.",
        "history_overview": "Overall Summary",
        "history_total_runs": "Total runs",
        "history_extracted": "Extracted phenotypes",
        "history_verified_total": "Successfully verified",
        "history_success_rate": "Verification Success Rate",
        "history_coverage": "Model Coverage",
        "history_coverage_help": "Ratio between phenotypes extracted by LLM and total attractors allowed by the mathematical model.",
        "history_coverage_na_help": "Run new tests with the latest verifier version to compute this.",
        "history_tab_stats": "Statistics & Charts",
        "history_tab_failures": "Failure Analysis",
        "history_tab_details": "Detailed Runs",
        "history_chart_success_by_llm": "Verification Success Rate by LLM",
        "history_chart_coverage_by_llm": "Model Coverage by LLM",
        "history_chart_no_coverage": "No data available for coverage chart.",
        "history_chart_success_pct": "Success (%)",
        "history_chart_coverage_pct": "Coverage (%)",
        "history_table_header": "Detailed table of all runs",
        "history_export_csv": "Download table as CSV",
        "history_failures_header": "Failed Extractions Overview (NOT VERIFIED)",
        "history_failures_info": "All phenotypes that were extracted but not confirmed by the mathematical model are listed here. Useful for identifying hallucinations or bad prompting.",
        "history_no_failures": "Great news! No failed phenotypes recorded yet.",
        "history_filter_llm": "Filter by LLM model:",
        "history_filter_all": "All",
        "history_failures_rationale": "Detailed Rationale Listing",
        "history_failure_variables": "**Proposed variables and states:**",
        "history_failure_rationale_label": "**Model reasoning (Why it thought it should be this way):**",
        "history_source_run": "Source run: {file}",
        "history_details_header": "Raw JSON Results Viewer",
        "history_details_select_run": "Select a file to view details:",
        "history_details_prompt_label": "**Prompt used:**",
        "history_details_results_label": "**Results:**",
        "history_details_error_msg": "This run failed and contains no phenotypes. The LLM returned this error instead:",
        "history_details_nonstandard": "Non-standard output: {item}",
        "history_tokens_prompt": "Request tokens",
        "history_tokens_response": "Response tokens",
        "history_tokens_total": "Total tokens",
        "history_read_error": "Error reading {file}: {error}",
        "history_col_datetime": "Date & Time",
        "history_col_llm": "Model (LLM)",
        "history_col_input": "Input (Data)",
        "history_col_aeon": "AEON Model",
        "history_col_attractors": "Model Attractors",
        "history_col_phenotypes": "Extracted Phenotypes",
        "history_col_verified": "Verified",
        "history_col_success_rate": "Verification Success (%)",
        "history_col_coverage": "Model Coverage (%)",
        "history_col_file": "File",
        "history_col_tokens": "Used tokens",
        "history_col_milestone": "Milestone",
        "history_milestone_label": "Show milestone:",
        "history_milestone_all": "All",
        "history_milestone_prefix": "Milestone",
        "history_col_run_count": "# Runs",
        "history_col_correct_runs": "Correct",
        "history_col_incorrect_runs": "Incorrect",
        "history_col_avg_tokens": "Ø Tokens",
        "history_correct_runs_metric": "Correct Runs",
        "history_incorrect_runs_metric": "Incorrect Runs",
        "history_rebuild_index_label": "Run Index Management",
        "history_rebuild_index_help": "The index is updated automatically on every new run. If you have imported old JSON files manually, use this to rebuild the index.",
        "history_rebuild_index_btn": "Rebuild full index",
        "history_rebuild_index_spinner": "Indexing...",
        "history_rebuild_index_done": "Index rebuilt successfully for {n} runs.",
        "history_refresh_btn": "Refresh data",
        "history_llm_table_header": "LLM Overview",
        "history_llm_table_group_by_model": "Group by LLM + Model",
        "history_llm_table_group_by_model_help": "Enable to break down results by LLM and the tested AEON model.",
        "history_milestone_summary_header": "Summary by Milestone",
        "history_milestone_export_csv": "Download milestone summary as CSV",
        "history_milestone_export_filename": "milestone_summary_{date}.csv",
        "history_fail_col_llm": "LLM Model",
        "history_fail_col_phenotype": "Phenotype Name",
        "history_fail_col_rationale": "Rationale",
        "history_fail_col_variables": "Extracted Variables",
        "history_fail_col_file": "File",
        "history_unknown_llm": "Unknown",
        "history_unknown_input": "Unknown",
        "history_unknown_model": "Unknown",
        "history_unknown_phenotype": "Unknown",
        "history_no_rationale": "No rationale provided",

        # Diagnostics tab
        "history_tab_diagnostics": "Failure Diagnostics",
        "history_diag_header": "Interactive Inconsistency Diagnostics",
        "history_diag_info": "Phenotypes that were extracted but not confirmed by the mathematical model are listed here. Categorise them for the thesis discussion. Data is saved automatically.",
        "history_diag_cat_unclassified": "Unclassified",
        "history_diag_cat_hallucination": "Logical Hallucination",
        "history_diag_cat_misinterpretation": "Contextual Misinterpretation",
        "history_diag_cat_discrepancy": "Model Discrepancy",
        "history_diag_rationale_label": "**Rationale:**",
        "history_diag_extracted_label": "**Extracted from text (LLM):**",
        "history_diag_compare_popover": "Compare extraction against model (Differences)",
        "history_diag_compare_desc": "Detailed comparison of what the LLM found against the possible states in the AEON model.",
        "history_diag_no_attractor_details": "No attractor details were saved for this model.",
        "history_diag_attractor_tab": "Attractor #{id}",
        "history_diag_matches": "**Matches ({n}):**",
        "history_diag_incorrect": "**Incorrect state ({n}):**",
        "history_diag_incorrect_item": "- `{k}`: LLM proposed `{got}`, but model requires `{expected}`",
        "history_diag_hallucinated": "**Hallucinated variables ({n}):**",
        "history_diag_hallucinated_item": "- `{k}`: Does not exist in model",
        "history_diag_missing_expander": "Missing variables in extraction ({n})",
        "history_diag_missing_desc": "These variables make up the rest of the attractor, but the LLM did not extract them from the text:",
        "history_diag_compare_error": "Failed to load comparison: {error}",
        "history_diag_stats_header": "Failure Statistical Profile",
        "history_diag_col_category": "Category",
        "history_diag_col_count": "Count",
        "history_diag_no_errors": "No errors have been recorded for this selection yet.",
        "history_diag_progress_label": "**Overall analysis progress:**",
        "history_diag_progress_count": "Classified: {analyzed} / {total}",
        "history_diag_download_btn": "Download diagnostics (CSV)",
        "history_diag_download_confirm": "Confirm download",
        "history_diag_export_col": "Expert Category",
        "history_diag_export_filename": "failure_diagnostics_{date}.csv",
        "history_diag_classify_label": "Classify error:",

        # Optional sections
        "history_show_runs_toggle": "Show all runs ({n})",
        "history_download_runs_csv": "Download runs as CSV",
        "history_show_failures_toggle": "Load failure analysis",
        "history_failures_hidden_hint": "{n} unverified phenotypes — toggle on to load analysis",

        # Models
        "models_fetch_error": "Failed to fetch models from e-INFRA API: {error}",
        "models_gemini_fetch_error": "Failed to fetch Gemini models: {error}",

        # Extractor
        "extractor_init_error": "Critical error initialising model {model}: {error}",
        "extractor_dir_missing": "Error: Directory {path} does not exist.",
        "extractor_prompt_intro": "Analyse the following materials (text and images) and extract phenotypes from them:",
        "extractor_model_context_header": "\n\n--- CONTEXT: COMPUTATIONAL MODEL ({name}) ---\nThe exact variable names (IDs) you must use are defined here:\n\n",
        "extractor_model_context_footer": "--------------------------------------------------\nWARNING: Do not use generic names (e.g. 'NF-kB'), instead find the corresponding ID in the list above (e.g. 'v_NfkB_H').\n",
        "extractor_model_load_error": "Failed to load model: {error}",
        "extractor_text_section": "\n--- TEXT FROM {name} ---\n{text}",
        "extractor_api_error": "API error during extraction (Model: {model}): {error}",

        # Testing (background jobs)
        "testing_cancelled_before_extraction": "Cancelled before extraction.",
        "testing_cancelled_before_verification": "Cancelled before verification.",
        "testing_bg_active": ":material/sync: {n} active",
        "testing_bg_all_done": "All jobs finished",

        # Config
        "config_save_error": "Error saving {name}: {error}",
    }
}

ICONS = {
    "page_icon": "🧬",           # must stay emoji – used as Streamlit page_icon
    "app": ":material/account_tree:",
    "nav_testing": ":material/science:",
    "nav_data": ":material/folder_managed:",
    "nav_history": ":material/bar_chart:",
    "folder": ":material/folder:",
    "download": ":material/download:",
    "delete": ":material/delete:",
    "save": ":material/save:",
    "run": ":material/play_arrow:",
    "warning": ":material/warning:",
    "error": ":material/error:",
    "success": ":material/check_circle:",
    "progress": ":material/hourglass_empty:",
    "log": ":material/notes:",
    "verified": ":material/check_circle:",
    "not_verified": ":material/cancel:",
    "search": ":material/search:",
    "chart": ":material/pie_chart:",
    "classified": ":material/task_alt:",
    "unclassified": ":material/pending:",
    "incorrect": ":material/dangerous:",
    "hallucinated": ":material/warning:",
    "cancel": ":material/stop_circle:",
    "jobs": ":material/background_replace:",
    "status_pending":   ":material/hourglass_empty:",
    "status_running":   ":material/sync:",
    "status_done":      ":material/check_circle:",
    "status_failed":    ":material/cancel:",
    "status_cancelled": ":material/block:",
    "correct": ":material/check_circle:",
    "other":   ":material/close:",
}


def get_lang() -> str:
    """Return current language code from session state, defaulting to Slovak.
    Safe to call from background threads (no Streamlit context)."""
    try:
        import streamlit as st
        return st.session_state.get("lang", "sk")
    except Exception:
        return "sk"


def t(key: str, **kwargs) -> str:
    """Translate a key for the current language, with optional format arguments."""
    lang = get_lang()
    text = TRANSLATIONS.get(lang, TRANSLATIONS["sk"]).get(key, key)
    if kwargs:
        text = text.format(**kwargs)
    return text


def render_language_switcher():
    """Render language toggle in sidebar."""
    import streamlit as st
    options = {"Slovenčina 🇸🇰": "sk", "English 🇬🇧": "en"}
    current = st.session_state.get("lang", "sk")
    current_label = next(k for k, v in options.items() if v == current)
    chosen = st.sidebar.selectbox(
        t("language_label"),
        list(options.keys()),
        index=list(options.keys()).index(current_label),
        key="_lang_switcher"
    )
    st.session_state["lang"] = options[chosen]

