"""
Environment Variable Export Module
Export passwords as environment variables or .env files
"""

from typing import Dict, List, Optional
from .core import get_password, list_all_keys


def export_as_env(
        keys: Optional[List[str]] = None,
        prefix: str = "",
        uppercase: bool = True,
        format_style: str = "export"
) -> Dict[str, str]:
    """
    Export passwords as environment variable strings

    Args:
        keys: Specific keys to export (None = all keys)
        prefix: Prefix to add to variable names
        uppercase: Convert variable names to uppercase
        format_style: 'export' (bash), 'set' (windows), or 'plain'

    Returns:
        Dict mapping variable names to export statements
    """
    if keys is None:
        keys = list_all_keys()

    if not keys:
        return {}

    exports = {}

    for key in keys:
        password = get_password(key)
        if password is None:
            continue

        # Format variable name
        var_name = f"{prefix}{key}"
        if uppercase:
            var_name = var_name.upper()

        # Format based on style
        if format_style == "export":
            exports[key] = f'export {var_name}="{password}"'
        elif format_style == "set":
            exports[key] = f'set {var_name}={password}'
        elif format_style == "plain":
            exports[key] = f'{var_name}="{password}"'
        else:
            exports[key] = f'{var_name}="{password}"'

    return exports


def generate_env_file(
        output_path: str,
        keys: Optional[List[str]] = None,
        prefix: str = "",
        uppercase: bool = True,
        include_comments: bool = True
) -> Dict[str, any]:
    """
    Generate a .env file from stored passwords

    Args:
        output_path: Path to write .env file
        keys: Specific keys to include (None = all)
        prefix: Prefix for variable names
        uppercase: Convert names to uppercase
        include_comments: Add header comments

    Returns:
        Result dict with success status and stats
    """
    if keys is None:
        keys = list_all_keys()

    if not keys:
        return {
            'success': False,
            'message': 'No passwords found to export',
            'count': 0
        }

    lines = []

    # Add header comments
    if include_comments:
        lines.append("# Environment variables generated by kcpwd")
        lines.append("# WARNING: This file contains sensitive data!")
        lines.append("# Do not commit to version control")
        lines.append("")

    # Export each password
    exported = 0
    failed = []

    for key in keys:
        password = get_password(key)
        if password is None:
            failed.append(key)
            continue

        # Format variable name
        var_name = f"{prefix}{key}"
        if uppercase:
            var_name = var_name.upper()

        # Add to file
        lines.append(f'{var_name}="{password}"')
        exported += 1

    # Write to file
    try:
        with open(output_path, 'w') as f:
            f.write('\n'.join(lines) + '\n')

        return {
            'success': True,
            'message': f'Exported {exported} passwords to {output_path}',
            'count': exported,
            'failed': failed
        }
    except Exception as e:
        return {
            'success': False,
            'message': f'Failed to write file: {str(e)}',
            'count': 0,
            'failed': keys
        }


def print_env_exports(
        keys: Optional[List[str]] = None,
        prefix: str = "",
        uppercase: bool = True,
        format_style: str = "export"
) -> int:
    """
    Print environment variable exports to stdout

    Args:
        keys: Specific keys to export
        prefix: Variable name prefix
        uppercase: Convert to uppercase
        format_style: Output format

    Returns:
        Number of variables exported
    """
    exports = export_as_env(keys, prefix, uppercase, format_style)

    for export_line in exports.values():
        print(export_line)

    return len(exports)