# -*- coding: utf-8 -*-
"""
ui_help_en.py

English help texts for the MigMan/DataMate configuration UI (NiceGUI).

Design goal:
- ui.py remains UI/controller logic
- ui_help_en.py contains only help content + small lookup API

Note:
- Keys are chosen so that they work directly with `active["value"]` (Global/Setup/Extract/Transform/Load/Overview)
  and `transform_tab_state["value"]` (Join/Mapping/Non-Empty/Duplicate).
"""

from __future__ import annotations

from typing import Dict, Optional


# ----------------------------
# Public API
# ----------------------------
def get_help_markdown_en(active_section: str, transform_tab: Optional[str] = None) -> str:
    """
    Returns the appropriate Markdown help text for the current UI context.

    Args:
        active_section: e.g., "Global", "Setup", "Extract", "Transform", "Load", "Overview"
        transform_tab:  e.g., "Join", "Mapping", "Non-Empty", "Duplicate" (only relevant when active_section="Transform")
    """
    section = (active_section or "Global").strip()

    if section == "Transform":
        tab = (transform_tab or "Join").strip()
        key = f"Transform/{tab}"
        return HELP_TEXT_MD_EN.get(key) or HELP_TEXT_MD_EN.get("Transform") or DEFAULT_HELP_MD_EN

    return HELP_TEXT_MD_EN.get(section) or DEFAULT_HELP_MD_EN


def get_help_title_en(active_section: str, transform_tab: Optional[str] = None) -> str:
    """Short title (e.g., for dialog header)."""
    section = (active_section or "Global").strip()
    if section == "Transform":
        tab = (transform_tab or "Join").strip()
        return f"Help – Transform → {tab}"
    return f"Help – {section}"


# ----------------------------
# Contents (EN)
# ----------------------------
DEFAULT_HELP_MD_EN = """## Help

No help text is available for this section yet.

**Tip:** If you briefly tell me *what* exactly you want to explain here (target audience, workflow, typical errors),
I can add the text precisely.
"""


HELP_TEXT_MD_EN: Dict[str, str] = {
    "Global": """## Global

Here you control the UI itself and the saving/resetting.

- **Save**: writes your changes to the local configuration (delta to the default configuration).
- **Reset**: resets the local configuration to default (with confirmation).
- **Dark mode**: toggle UI appearance.

**Typical pitfalls**

- Changes are only "active" after an input (Save becomes relevant then).
- In case of "weird" UI behavior: save once, reload the page, check again.

**Convention**

- Paths (e.g., `etl_directory`) are relative to the working directory.
""",

    "Setup": """## Setup

Basic configuration: *Which projects? Which adapters? Which additional lists?*

##### Data Source Adapter
Choose the source adapter (e.g., SAP/ODBC/Proalpha). This determines, among other things:

- which tables/objects are suggested as default,
- which adapter-specific parameters are visible in the **Extract** section.

##### Target Adapter
Choose the target adapter for the Load step.

##### Project Status File (optional)
- Imports projects from an Excel status file (if available).
- Useful for initial population – afterwards, it is often maintained directly in the UI.

##### Projects
- Projects/objects are the "workload" for Extract/Transform/Load.
- **Select All / Select None** helps with a quick start.

##### Multi-Project Lists
- **Feature assignment keys**: comma-separated (e.g., `key1, key2`).
- **Text keys**: comma-separated (e.g., `de, en`).

**Typical pitfalls**

- Empty key lists should be removed (do not leave as `[]`) to avoid subsequent errors.
""",

    "Extract": """## Extract

Controls data acquisition (DB or files) and input parameters.

##### General Extract Settings
- **Extract active**: Extraction completely on/off.
- **Load to Nemo**: uploads extracts to Nemo as well (for analysis/transparency).
- **Delete temp files**: cleans up temporary files after use.
- **Nemo project prefix**: Prefix for extract tables (e.g., `MME...`).

**Prefix concept (recommended, keep consistent)**

- `MME...` = *MigMan Extract* (raw extracts)
- `MMT...` = *MigMan Transform* (intermediate results from transform steps)
- `MML...` = *MigMan Load* (final load/export tables, relevant for Proalpha import)

##### Extract method
- `database`: direct extraction from the source (e.g., SAP/ODBC).
- `file`: import from CSV files – useful when only exports are provided.

##### Tables
- Select tables/objects to be extracted.
- **Add custom table**: adds a table not in the default list.

##### Extract from folder
- Path to the file source (especially for `file`).
- The UI shows a quick plausibility check (exists? CSV count?).

##### Quick Setup (for Extract method = file)
- can automatically generate file configs for the tables stored in the adapter.

##### File Configuration
- Import parameters per file (Separator, Encoding, Header, Columns, …).
- Goal: robust, reproducible file import without manual rework.

**Typical pitfalls**

- If you add tables/configs but the UI does not update immediately: switch to another tab and back.
- Separator/Encoding must match the provided files (otherwise "skewed" columns).
""",

    "Transform": """## Transform

Processes/normalizes the extracted data.

Sub-tabs:
- **Join**: Create data model (SQL join statements).
- **Mapping**: Assignments (e.g., recoding, normalization).
- **Non-Empty**: Mandatory fields/validation rules.
- **Duplicate**: Duplicate check (Fuzzy logic / Matching).

The help in the "?" automatically adapts to the active Transform tab.
""",

    "Transform/Join": """## Transform → Join

Here the data model is created (typically via SQL).

**Purpose?**
- A target structure is built from multiple source tables, which is later used for analysis/load.

**Workflow**

1. Select project/object (e.g., Suppliers).
2. **Customize** generates/opens the join SQL for the object.
3. Adjust SQL in the editor (field names, joins, filters).
4. Execute transfer and check results.

**Typical pitfalls**

- Missing or non-unique join keys → leads to duplicates or missing records.
- A field is referenced in Duplicate/Non-Empty but is not present in the join → subsequent run fails.
- Case sensitivity can be relevant (especially for field/attribute names in subsequent steps).

**Tip**

- Stabilize the join first, then activate Mapping/Non-Empty/Duplicate.
""",

    "Transform/Mapping": """## Transform → Mapping

Mapping is used for normalizing/recoding values and field assignments.

**Typical use cases**

- Adjust number ranges (e.g., remove/set leading digits).
- Implement codes/keys (e.g., CASE logic not in the join, but as mapping).
- Allow synonyms/alternative field names (depending on UI configuration).

**Important**
- Field/attribute names are often **case-sensitive**: write them exactly as they appear in the data model.

**Typical pitfalls**

- After "Add", the view does not update immediately → switch to another tab and back.
- CSV/mapping files not properly formatted (delimiter/quotes) → leads to incorrect assignments.

**Tipp**

- Keep mapping as *central* as possible (do not "hide" it in Join SQL) to ensure reusability.
""",

    "Transform/Non-Empty": """## Transform → Non-Empty

Rules for mandatory fields / non-empty values.

**Purpose?**

- Data quality: Fields that must be filled for the load are checked.
- Helps to make errors visible early (before importing into Proalpha/MigMan).

**Typical pitfalls**

- Too many mandatory fields at once → many errors, little focus.
- Mandatory fields reference fields not generated in the join.

**Tip**

- Start with a few core mandatory fields and expand iteratively.
""",

    "Transform/Duplicate": """## Transform → Duplicate

Duplicate check per object (e.g., Customers/Suppliers/Prospects).

**Core concept**

- For each object, you define which fields are included in the comparison.
- A **Similarity Threshold** controls when records are considered "similar".

**Add custom field**

- Adds an additional field to the comparison list (for matching/tokenization).
- Field names must be exact (including case) as in the model.

**Typical pitfalls**

- Field configured in Duplicate but not present in Join → run fails.
- UI refresh after adding/deleting: if not visible, switch tab briefly and back.
- Performance: too many fields/too low threshold can significantly increase runtime.

**Tip**

- Start lean (few, stable fields) and expand gradually.
""",

    "Load": """## Load

Controls the output/loading into the target system.

**Purpose?**

- Generates the final load projects/export data (for Proalpha/MigMan).
- Typically, the prefix `MML...` (*MigMan Load*) is used, i.e., "the" table you need at the end for import.
- Optional features like "Delete projects before load" help ensure a clean rerun.

**Typical pitfalls**

- Order/dependencies: master data before transaction data.
- Fields/data types do not match import templates → check with a test run first.

**Tip**

- For initial iterations, activate as few objects as possible and test thoroughly.
""",

    "Overview": """## Overview

Overview of the current configuration deltas.

**Purpose?**

- Quick "sanity check" of what you have changed compared to the default configuration.
- Helps with debugging: "Why is it running differently than before?"

**Tip**

- If something is unexpected: open Overview, check changes, then revert selectively.
""",
}

# -------------------- Tooltips --------------------
TOOLTIP_TEXT_EN = {
    "setup.source_adapter": "Select the source adapter used for extraction (e.g., PROALPHA, INFOR, ODBC).",
    "setup.project_status_file": "Path to an Excel file used to import/manage project status information.",
    "setup.mult_project_list_feature_assignments": "Comma-separated keys for feature assignments (e.g., key1, key2).",
    "setup.mult_project_list_text": "Comma-separated keys for text projects (e.g., text1, text2).",
    "extract.quick_setup.create_file_configs": "Automatically creates file configs for all tables of the selected adapter (CSV paths based on 'Extract from folder').",
    "extract.chunk_size": "Number of records per batch during extraction (tune for performance/memory).",
    "extract.timeout": "Timeout in seconds for DB queries/connections in Extract.",
    "extract.table_prefix": "Optional prefix for table names (e.g., schema/tenant).",
    "extract.table_selector": "Table filter/selector (pattern or selection depending on adapter).",
    "extract.add_custom_table": "Add custom tables that are not part of the default list.",
    "extract.add_custom_table_apply": "Adds the entered table to the selectable list.",
    "transform.general.active": "Enables/disables the entire Transform phase.",
    "transform.general.load_to_nemo": "When enabled, prepares transform output for Nemo import.",
    "transform.general.delete_temp_files": "Deletes temporary files after a successful run.",
    "transform.general.dump_files": "Writes debug/dump files for analysis (may consume disk space).",
    "transform.general.nemo_project_prefix": "Project prefix for Nemo projects in the Transform phase.",
    "transform.join.active": "Enables/disables Join transformations.",
    "transform.join.customize_project": "Opens the project-specific join configuration (overrides defaults for this project).",
    "transform.mapping.new_field_name": "Target field name for a new field mapping (written into the mapping configuration).",
    "transform.nonempty.active": "Removes empty/NULL columns during transformation.",
    "transform.duplicate.active": "Enables/disables duplicate detection in Transform.",
    "transform.duplicate.object_active": "Enables/disables duplicate detection for this object (e.g., Customers).",
    "transform.duplicate.primary_key": "Primary key field for this object (unique identification).",
    "transform.duplicate.add_custom_field": "Adds additional fields to duplicate matching (comma-separated values supported).",
    "transform.duplicate.add_custom_field_apply": "Applies the input and updates the fields list.",
    "load.active": "Enables/disables the Load phase (import into Nemo).",
    "load.delete_temp_files": "Deletes temporary files after Load.",
    "load.delete_projects_before_load": "Deletes existing projects before importing (use with care).",
    "load.nemo_project_prefix": "Project prefix for Nemo projects in Load (default: mml).",
        "global.etl_directory": "Path to the ETL working directory (base folder for local ETL files/configs).",
    "setup.target_adapter": "Select the target adapter for Load (e.g., PROALPHA_MIGMAN or NEMO_BUSINESS_PROCESSES).",
    "extract.general.active": "Enables/disables the entire Extract phase.",
    "extract.general.load_to_nemo": "When enabled, prepares/passes extract results for Nemo import.",
    "extract.general.delete_temp_files": "Deletes temporary files after Extract (if generated).",
    "extract.general.method": "Extraction method: database = direct DB extraction, file = file-based import only (e.g., CSVs).",
    "transform.mapping.active": "Enables/disables Mapping (field mappings + transformation rules).",
    "setup.projects": "Select the projects/objects that should be processed in Extract, Transform and Load. Multiple selection and search are supported.",
    "extract.general.nemo_project_prefix": "Project prefix for Nemo projects in the Extract phase.",
    "extract.extract_from_folder": "Folder path for file-based extraction. The UI checks whether the path exists and how many CSV files are located there.",
    "extract.file.project": "Project name or table/object identifier for this file configuration.",
    "extract.table_prefixes": "Schema prefixes checked in order when resolving tables. Enter one prefix per line.",
     "global.save": "Saves your current changes as local configuration (delta to the default configuration).",
    "global.reset": "Discards all local customizations and resets the configuration to the default values.",
    "global.dark_mode": "Toggles the UI between light and dark appearance.",
    "global.help": "Opens the context-sensitive help for the currently visible section.",
    "open_etl_directory": "Open ETL directory",
    "open_extract_directory": "Open extract directory",
    "open_join_directory": "Open join directory",
    "open_mapping_directory": "Open mapping directory",
    "open_load_reports_directory": "Open reports directory",

    "setup.import_projects": "Imports projects from the specified Excel file and applies only valid projects from the MigMan data source.",
    "setup.projects.select_all": "Selects all available projects for Extract, Transform and Load.",
    "setup.projects.select_none": "Clears the project selection.",

    "extract.tables_select": "Select the tables/objects that should be extracted for the currently selected adapter.",
    "extract.adapter.odbc_connstr": "ODBC connection string used to access the source system. Typically contains driver, server, database and credentials.",
    "extract.sap.server_address": "Host name or server name of the SAP HANA instance.",
    "extract.sap.database_name": "Name of the target database inside SAP SystemDB.",
    "extract.sap.port": "Network port used for the SAP database connection.",
    "extract.sap.username": "User name for the database connection.",
    "extract.sap.password": "Password for the database connection.",
    "extract.sap.autocommit": "If enabled, queries are executed with autocommit. Change only if required by the environment.",

    "extract.file.active": "Enables or disables this individual file configuration within the Extract step.",
    "extract.file.path": "Full path to the source file. The file is validated for existence during configuration checks.",
    "extract.file.separator": "Delimiter used in the file, e.g. semicolon, comma or tab. Must match the provided file.",
    "extract.file.quote": "Quote character used for text fields in the file, usually double quotes.",
    "extract.file.dateformat": "Expected date format used while reading the file, e.g. %d-%m-%Y.",
    "extract.file.encoding": "Character encoding of the file, e.g. utf-8 or latin-1.",
    "extract.file.header": "Indicates whether the first row contains column headers.",
    "extract.file.all_varchar": "Imports all columns as text to avoid type conflicts and conversion errors during file import.",
    "extract.file.columns": "Column names for files without a header row. Order and count must match the file.",
    "extract.file.add_column": "Adds another column name to the manual column list.",
    "extract.file.check_configuration": "Checks file path, column count, delimiter and encoding by reading a sample from the file.",
    "extract.file.add_file": "Creates a new file configuration for file-based extraction.",

    "transform.join.limit": "Temporarily limits the number of rows processed in the Join step. Useful for development and debugging.",
    "transform.mapping.field_name": "Target model field for which a mapping or mapping file is maintained.",
    "transform.mapping.create_template": "Creates or extends a CSV mapping template with source values currently found in the join results.",
    "transform.mapping.source_field": "Source field that should be extended or normalized by synonyms.",
    "transform.mapping.synonym_fields": "Alternative field names that should be treated like the source field.",

    "transform.duplicate.threshold": "Similarity threshold in percent. Higher values are stricter, lower values find more potential duplicates.",
    "transform.duplicate.fields": "Fields included in duplicate matching. These fields must exist in the join result.",
    "transform.duplicate.object_name": "Name of the object for which a dedicated duplicate rule is created.",

    "load.development_deficiency_mining_only": "Runs only the development path for deficiency mining instead of the full standard load.",
    "load.development_load_reports_only": "Loads only report/output artifacts for development or test purposes.",
}

def get_tooltip_en(key: str, default: str = "") -> str:
    return TOOLTIP_TEXT_EN.get(key, default)
