"""Internationalization module for Prozes."""

import os
from pathlib import Path

# Default language
_current_lang = 'en'

# Translations
TRANSLATIONS = {
    'en': {
        # Headers
        'creating_project_mvc': 'Creating MVC project',
        'creating_project_api': 'Creating REST API',
        'creating_project_cli': 'Creating CLI project',
        'creating_project_clean': 'Creating Clean Architecture project',

        # Steps
        'creating_folder_structure': 'Creating folder structure...',
        'creating_venv': 'Creating virtual environment...',
        'installing_deps': 'Installing dependencies...',
        'initializing_git': 'Initializing Git repository...',

        # Success messages
        'venv_created': 'Virtual environment created',
        'deps_installed': 'Dependencies installed',
        'git_initialized': 'Git repository initialized',
        'structure_mvc_created': 'MVC structure created',
        'structure_api_created': 'REST API structure created',
        'structure_cli_created': 'CLI structure created',
        'structure_clean_created': 'Clean Architecture structure created',
        'requirements_created': 'requirements.txt created',
        'project_created': 'Project created successfully!',

        # Error messages
        'error_creating_project': 'Error creating project',
        'venv_already_exists': 'Virtual environment already exists',
        'venv_not_found': 'Virtual environment not found',
        'python_not_found': 'Python version {version} not found',
        'requirements_not_found': 'Requirements file not found',
        'git_not_found': 'Git not found. Make sure Git is installed.',

        # Validation messages
        'validation_name_empty': 'Project name cannot be empty',
        'validation_name_start': 'Project name must start with a letter or underscore',
        'validation_name_chars': 'Project name can only contain letters, numbers, and underscores',
        'validation_name_keyword': "'{name}' is a Python reserved keyword",
        'validation_project_exists': "Project '{name}' already exists in the current directory",
        'validation_python_version_format': "Invalid Python version format: '{version}'. Use format like 3.8 or 3.11",
        'validation_git_not_available': 'Git is not installed or not available in PATH',
        'validation_install_deps_requires_venv': '--install-deps requires --venv to be specified',
        'validation_errors_header': 'Validation errors',

        # Summary table
        'project': 'Project',
        'type': 'Type',
        'venv': 'Venv',
        'git': 'Git',
        'deps': 'Deps',
        'created': 'Created',
        'initialized': 'Initialized',
        'installed': 'Installed',

        # Next steps
        'next_steps': 'Next steps',
        'activate_venv_win': '(Windows)',
        'activate_venv_unix': '(Linux/Mac)',
        'open_docs': 'Open',

        # CLI Help texts
        'help_main': 'Prozes - Python project generator with predefined architectures.',
        'help_lang': 'Language (en=English, pt=Portuguese). Uses global config if not specified.',
        'help_verbose': 'Verbose mode',
        'help_git': 'Initialize Git repository',
        'help_venv': 'Create virtual environment',
        'help_python_version': 'Python version for venv (e.g., 3.11)',
        'help_install_deps': 'Install dependencies automatically',

        'help_mvc': 'Create a project with MVC architecture.',
        'help_mvc_long': 'Structure with Models, Views, Controllers, templates and static files.',
        'help_mvc_type': 'Project type (default: web-flask)',

        'help_api': 'Create a pure REST API (no frontend).',
        'help_api_long': 'Lean structure focused on REST endpoints.',
        'help_api_type': 'API framework (default: fastapi)',

        'help_cli': 'Create a CLI project with Click.',
        'help_cli_long': 'Structure for command-line applications.',

        'help_clean': 'Create a project with Clean Architecture.',
        'help_clean_long': '''Structure:
  src/entities/     - Domain entities
  src/use_cases/    - Use cases (business rules)
  src/adapters/     - Repositories, Presenters
  src/frameworks/   - External frameworks (web, db)''',
        'help_clean_type': 'Web framework (default: flask)',

        'help_config': 'Configure Prozes settings.',
        'help_config_lang': 'Set default language (en=English, pt=Portuguese)',
        'help_config_show': 'Show current configuration',
    },
    'pt': {
        # Headers
        'creating_project_mvc': 'Criando projeto MVC',
        'creating_project_api': 'Criando API REST',
        'creating_project_cli': 'Criando projeto CLI',
        'creating_project_clean': 'Criando projeto Clean Architecture',

        # Steps
        'creating_folder_structure': 'Criando estrutura de pastas...',
        'creating_venv': 'Criando ambiente virtual...',
        'installing_deps': 'Instalando dependencias...',
        'initializing_git': 'Inicializando repositorio Git...',

        # Success messages
        'venv_created': 'Ambiente virtual criado',
        'deps_installed': 'Dependencias instaladas',
        'git_initialized': 'Repositorio Git inicializado',
        'structure_mvc_created': 'Estrutura MVC criada',
        'structure_api_created': 'Estrutura API REST criada',
        'structure_cli_created': 'Estrutura CLI criada',
        'structure_clean_created': 'Estrutura Clean Architecture criada',
        'requirements_created': 'requirements.txt criado',
        'project_created': 'Projeto criado com sucesso!',

        # Error messages
        'error_creating_project': 'Erro ao criar projeto',
        'venv_already_exists': 'Ambiente virtual ja existe',
        'venv_not_found': 'Ambiente virtual nao encontrado',
        'python_not_found': 'Python versao {version} nao encontrado',
        'requirements_not_found': 'Arquivo de requirements nao encontrado',
        'git_not_found': 'Git nao encontrado. Certifique-se de que o Git esta instalado.',

        # Validation messages
        'validation_name_empty': 'Nome do projeto nao pode ser vazio',
        'validation_name_start': 'Nome do projeto deve comecar com uma letra ou underscore',
        'validation_name_chars': 'Nome do projeto pode conter apenas letras, numeros e underscores',
        'validation_name_keyword': "'{name}' e uma palavra reservada do Python",
        'validation_project_exists': "Projeto '{name}' ja existe no diretorio atual",
        'validation_python_version_format': "Formato de versao Python invalido: '{version}'. Use formato como 3.8 ou 3.11",
        'validation_git_not_available': 'Git nao esta instalado ou nao esta disponivel no PATH',
        'validation_install_deps_requires_venv': '--install-deps requer que --venv seja especificado',
        'validation_errors_header': 'Erros de validacao',

        # Summary table
        'project': 'Projeto',
        'type': 'Tipo',
        'venv': 'Venv',
        'git': 'Git',
        'deps': 'Deps',
        'created': 'Criado',
        'initialized': 'Inicializado',
        'installed': 'Instalado',

        # Next steps
        'next_steps': 'Proximos passos',
        'activate_venv_win': '(Windows)',
        'activate_venv_unix': '(Linux/Mac)',
        'open_docs': 'Abrir',

        # CLI Help texts
        'help_main': 'Prozes - Gerador de projetos Python com arquiteturas predefinidas.',
        'help_lang': 'Idioma (en=Ingles, pt=Portugues). Usa config global se nao especificado.',
        'help_verbose': 'Modo detalhado',
        'help_git': 'Inicializar repositorio Git',
        'help_venv': 'Criar ambiente virtual',
        'help_python_version': 'Versao do Python para venv (ex: 3.11)',
        'help_install_deps': 'Instalar dependencias automaticamente',

        'help_mvc': 'Criar projeto com arquitetura MVC.',
        'help_mvc_long': 'Estrutura com Models, Views, Controllers, templates e arquivos estaticos.',
        'help_mvc_type': 'Tipo do projeto (padrao: web-flask)',

        'help_api': 'Criar uma API REST pura (sem frontend).',
        'help_api_long': 'Estrutura enxuta focada em endpoints REST.',
        'help_api_type': 'Framework da API (padrao: fastapi)',

        'help_cli': 'Criar projeto CLI com Click.',
        'help_cli_long': 'Estrutura para aplicacoes de linha de comando.',

        'help_clean': 'Criar projeto com Clean Architecture.',
        'help_clean_long': '''Estrutura:
  src/entities/     - Entidades do dominio
  src/use_cases/    - Casos de uso (regras de negocio)
  src/adapters/     - Repositorios, Presenters
  src/frameworks/   - Frameworks externos (web, db)''',
        'help_clean_type': 'Framework web (padrao: flask)',

        'help_config': 'Configurar opcoes do Prozes.',
        'help_config_lang': 'Definir idioma padrao (en=Ingles, pt=Portugues)',
        'help_config_show': 'Mostrar configuracao atual',
    },
}


def set_language(lang: str):
    """Set the current language."""
    global _current_lang
    if lang in TRANSLATIONS:
        _current_lang = lang
    else:
        _current_lang = 'en'


def get_language() -> str:
    """Get the current language."""
    return _current_lang


def t(key: str, **kwargs) -> str:
    """Get translated string by key.

    Args:
        key: Translation key
        **kwargs: Format arguments for the string

    Returns:
        Translated string, or the key if not found
    """
    lang_dict = TRANSLATIONS.get(_current_lang, TRANSLATIONS['en'])
    text = lang_dict.get(key, key)

    if kwargs:
        try:
            text = text.format(**kwargs)
        except KeyError:
            pass

    return text


def load_language_from_env():
    """Load language from PROZEES_LANG environment variable."""
    lang = os.environ.get('PROZEES_LANG', 'en').lower()
    set_language(lang)


def load_language_from_config():
    """Load language from config file if exists."""
    config_paths = [
        Path.home() / '.prozes' / 'config',
        Path.home() / '.config' / 'prozes' / 'config',
    ]

    for config_path in config_paths:
        if config_path.exists():
            try:
                content = config_path.read_text().strip()
                for line in content.split('\n'):
                    if line.startswith('lang=') or line.startswith('language='):
                        lang = line.split('=')[1].strip()
                        set_language(lang)
                        return
            except Exception:
                pass

    # Fallback to environment variable
    load_language_from_env()


# Initialize language on module load
load_language_from_config()
