#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
ChitraGupt OSINT Framework CLI.

This module serves as the entry point for the CLI. It uses argparse to parse a single
command argument (e.g., "init") and an optional --config parameter to specify the path to
the configuration file, then dispatches to the corresponding function.
"""

import argparse
import importlib.resources
import pathlib
import importlib
import sys
import typing

import msgspec

# Import logger configuration types
import chitragupt.core.logger as logger_mod


class Config(msgspec.Struct):
    """Overall configuration for starting ChitraGuptCLI."""

    logger: logger_mod.LoggerConfig
    enable_osint_util: typing.Optional[typing.Any] = None
    enable_browsers: typing.Optional[typing.Any] = None
    enable_general_browser: typing.Optional[typing.Any] = None
    enable_core_util: typing.Optional[bool] = None
    enable_cache: typing.Optional[bool] = None
    enable_dorkinator: typing.Optional[bool] = None


def start_chitragupt(data: Config) -> None:
    """
    Create and start the ChitraGuptCLI client using the provided configuration.

    Parameters
    ----------
    data : Config
        The decoded configuration object.
    """
    import chitragupt.client as client

    try:
        cli = client.ChitraGuptClientCLI(
            logger=logger_mod.GuptLogger(data.logger),
            enable_osint_util=data.enable_osint_util,
            enable_browsers=data.enable_browsers,
            enable_general_browser=data.enable_general_browser,
            enable_core_util=data.enable_core_util,
            enable_cache=data.enable_cache,
            enable_dorkinator=data.enable_dorkinator,
        )
        cli.start()
    except Exception as e:
        # Fallback: if an error occurs, log it and exit.
        logger_mod.GuptLogger(
            logger_mod.LoggerConfig(
                name="ChitraGupt", level=logger_mod.LogLevel.DEBUG
            )
        ).log(f"Error starting ChitraGuptCLI: {e}", logger_mod.LogType.ERROR)
        sys.exit(1)


def init_command(config_path: pathlib.Path) -> None:
    """
    Initialize the configuration file and start ChitraGuptCLI.

    If the configuration file (default "config.json") does not exist,
    this function copies the sample configuration from "chitragupt/assets/config.json".
    Then, it loads the configuration, decodes it using msgspec, and starts the CLI.

    Parameters
    ----------
    config_path : pathlib.Path
        The path to the configuration file.
    """
    fallback_logger = logger_mod.GuptLogger(
        logger_mod.LoggerConfig(
            name="ChitraGuptInit", level=logger_mod.LogLevel.DEBUG
        )
    )
    fallback_logger.log("Initializing ChitraGupt...", logger_mod.LogType.DEBUG)
    if config_path.is_file():
        fallback_logger.log(
            f"Configuration file '{config_path}' already exists.",
            logger_mod.LogType.DEBUG,
        )
    else:
        sample_config = importlib.resources.open_text(
            "chitragupt.assets", "config.json", encoding="utf-8"
        )
        try:
            sample_content = sample_config.read()
            config_path.write_text(sample_content, encoding="utf-8")
            fallback_logger.log(
                f"Created configuration file at '{config_path}' from sample.",
                logger_mod.LogType.INFO,
            )
        except Exception as e:
            fallback_logger.log(
                f"Error creating configuration file: {e}",
                logger_mod.LogType.ERROR,
            )
            sys.exit(1)
    # Now load and decode the configuration file.
    try:
        config_text = config_path.read_text(encoding="utf-8")
        config_obj: Config = msgspec.json.decode(config_text, type=Config)
        fallback_logger.log(
            "Configuration loaded successfully.", logger_mod.LogType.DEBUG
        )
    except Exception as e:
        fallback_logger.log(
            f"Error decoding configuration file: {e}",
            logger_mod.LogType.ERROR,
        )
        sys.exit(1)
    start_chitragupt(config_obj)


def main() -> None:
    """
    Parse command-line arguments and dispatch to the corresponding command function.

    Supported commands:
        - init: Initialize configuration and start ChitraGuptCLI.

    Optional arguments:
        --config PATH : Specify a custom path to the configuration file (default: config.json).
    """
    parser = argparse.ArgumentParser(
        prog="ChitraGupt", description="ChitraGupt OSINT Framework CLI"
    )
    parser.add_argument(
        "command", type=str, help="Command to execute (e.g., 'init')"
    )
    parser.add_argument(
        "--config",
        type=str,
        default="config.json",
        help="Path to the configuration file (default: config.json)",
    )
    args = parser.parse_args()

    command: str = args.command.lower()
    config_file = pathlib.Path(args.config)
    if command == "init":
        init_command(config_file)
    else:
        sys.stderr.write(
            f"Error: Command '{args.command}' is not recognized.\n"
        )
        sys.exit(1)
