#!/usr/bin/python3
"""
This module provides the command-line interface for the DCF (Detector Control Framework) GUI application.
It serves as a reference implementation of the ESO ELT ICS style and guidelines.

The application can connect to a DCF server either through:
- Consul service discovery (using a registered service name)
- Direct Req/Rep URI endpoint

Key responsibilities:
    - Parse and validate command-line arguments
    - Initialize Taurus application framework
    - Configure logging using WdglibLogger
    - Resolve service URI from Consul or direct input
    - Launch the main GUI window

Example usage:
    # Connect via Consul service name
    dcfGui --name ngc-req --log-level INFO

    # Connect via direct URI
    dcfGui --uri zpb.rr://127.0.0.1:12081 --log-level DEBUG


"""
import sys
from typing import Optional

import click
import taurus
from taurus.core.util import argparse
from taurus.core.util.log import Logger
from taurus.qt.qtgui.application import TaurusApplication
from taurus.external.qt.QtWidgets import QApplication

from ifw.wdglib.log.wdglib_logger import WdglibLogger
from dcf.gui.dcfGui.dcfguimainwindow import DcfGuiMainWindow

import ifw.core.stooUtils.consul as consul_utils
from ifw.core.utils.utils import find_file

@click.command('dcfGui')
@click.option('-n', '--name', default=None, help='Registered name in Consul, e.g. ngc-req')
@click.option('-u', '--uri', default=None, help='Service URI, e.g. zpb.rr://127.0.0.1:12081')
@click.option('-l', '--log-level', default='ERROR', help='Debugging Level',
               type=click.Choice(["TRACE", "CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"], 
                                 case_sensitive=False))
@click.pass_context
def main(ctx: click.Context, name: Optional[str], uri: Optional[str], log_level: str) -> None:
    """DCF GUI application entry point.
    
    Initializes the Taurus application framework, configures logging using WdglibLogger,
    validates command-line arguments, resolves the service URI, and launches the main GUI window.
    
    This function serves as the primary entry point for the DCF GUI application. It handles:
    - Application initialization with Taurus framework
    - Logging configuration from JSON config file
    - Validation that either Consul service name or direct URI is provided
    - Creation and display of the main GUI window
    
    Args:
        ctx: Click context object containing parsed command-line parameters.
        name: Optional Consul service name for service discovery (e.g., "ngc-req").
        uri: Optional direct Req/Rep URI endpoint (e.g., "zpb.rr://127.0.0.1:12081").
        log_level: Logging level for application output (TRACE, CRITICAL, ERROR, WARNING, INFO, DEBUG).
    
    Raises:
        SystemExit: If neither --name nor --uri is provided, the application exits with error code.
    
    Example:
        >>> main(ctx, name="ngc-req", uri=None, log_level="INFO")
        >>> main(ctx, name=None, uri="zpb.rr://127.0.0.1:12081", log_level="DEBUG")
    
    @ingroup dcfGui
    """

    app = TaurusApplication(
        app_name="dcfGui",
        app_version="0.2.0",
        org_name="ESO",
        org_domain="eso.org",
        cmd_line_parser=None,
    )


    
    logger = Logger(app.applicationName())
    logger.setLogLevel(getattr(taurus, log_level.title()))
    logger.info(f"Application LogLevel=|{log_level}|")

    if name is None and uri is None:
        logger.error(
            "DCF GUI needs a consul request service reference (command line option --name) or a Req/Rep URI endpoint (command line option --uri) to start"
        )
        print(
            "ERROR: DCF GUI needs a consul request service reference (command line option --name) or a Req/Rep URI endpoint (command line option --uri) to start"
        )
        sys.exit()

    logger_config_file_path = find_file("config/dcf/gui/dcfGui/dcfGui_logging.json")
    WdglibLogger.init(logger_config_file_path)
    WdglibLogger.set_application_name('Dcf')

    window = DcfGuiMainWindow(ctx, get_uri(ctx))
    window.setWindowTitle('DCF GUI')
    window.show()
    sys.exit(app.exec_())


def get_uri(cmd_line_ctx: click.Context) -> str:
    """Resolve the Req/Rep URI from command-line parameters.
    
    Resolves the service URI using one of two methods:
    - Consul service discovery: Queries Consul using the provided service name
    - Direct URI usage: Uses the provided URI after cleaning and validation
    
    The function ensures the returned URI is MAL-compatible by:
    - Removing trailing slashes
    - Stripping quotes (single and double)
    - Trimming whitespace
    
    Args:
        cmd_line_ctx: Click context object containing 'name' and 'uri' parameters
                      from command-line parsing.
    
    Returns:
        Cleaned URI string ready for MAL communication.
        
    Raises:
        Exception: If Consul lookup fails when name is provided and uri is None.
        ValueError: If neither name nor uri is available in context.
    
    Example:
        >>> ctx.params = {"name": "ngc-req", "uri": None}
        >>> get_uri(ctx)
        'zpb.rr://192.168.1.100:12081'  # Resolved from Consul
        
        >>> ctx.params = {"name": None, "uri": "zpb.rr://127.0.0.1:12081/"}
        >>> get_uri(ctx)
        'zpb.rr://127.0.0.1:12081'  # Trailing slash removed
    
    Note:
        Trailing slashes are removed to ensure MAL compatibility.
        When using Consul, the service name must be registered in the OLDB.
    """
    name = cmd_line_ctx.params.get("name")
    uri = cmd_line_ctx.params.get("uri")
    
    if uri is None:
        # Resolve URI from Consul using service name
        cons = consul_utils.ConsulClient()
        uri = cons.get_uri(name)
    else:
        # Clean user-provided URI
        uri = uri.strip(' " " ')
        uri = uri.strip(' \' \' ')
        # Remove trailing slash for MAL compatibility
        if uri.endswith('/'):
            uri = uri[:-1]
    
    return uri


if __name__ == "__main__":
    main()
