#!/usr/bin/env python3

import sys
from pathlib import Path
import importlib
import inspect
import types

from llxgvagate.error import GvaGateError   # pyright: ignore[reportMissingImports]
from llxgvagate.base_plugin import BasePlugin   # pyright: ignore[reportMissingImports]

from n4d.client import Client   # pyright: ignore[reportMissingImports]

class GvaGate:

    def __init__(self, args) -> None:

        self.plugins_path = Path('/usr/share/gva-gate/plugins')
        self.plugins: dict[str, BasePlugin] = {}
        if len(args) > 2:
            self.user = args[0]
            self.password = args[1]
            self.method = args[2]
        elif len(args) == 2:
            self.user = args[0]
            self.password = args[1]
            self.method = "id"
        else:
            sys.exit(GvaGateError.BadArguments)
        self.load_plugins()

    def load_plugins(self):
        for path in self.plugins_path.glob("*.py"):
            if path.name.startswith("_"):
                continue  # Ignorar __init__.py etc.
            
            try:
                loader = importlib.machinery.SourceFileLoader(path.stem, str(path))
                module = types.ModuleType(path.stem)
                loader.exec_module(module)

            except Exception as e:
                print(f"[warn] No se pudo cargar '{path.name}': {e}")
                continue

            for _, obj in inspect.getmembers(module, inspect.isclass):
                if issubclass(obj, BasePlugin) and obj is not BasePlugin:
                    try:
                        instance = obj()
                        self.plugins[instance.name.lower()] = instance
                    except Exception as e:
                        print(f"[warn] Error instanciando '{obj.__name__}': {e}")

    def process_exit_error(self, error):
        sys.exit(error)

    def sync_with_adi(self, method):
        n4d_remote = Client("https://server:9779")
        try:
            n4d_remote.GvaGate.store_id_user(self.user, self.password, method)
        except Exception:
            pass

    def run(self):
        m = self.method.lower()
        if m not in self.plugins.keys():
            self.process_exit_error(GvaGateError.BadArguments)
        user,error = self.plugins[m].authenticate(self.user, self.password, self.sync_with_adi)
        if error is not GvaGateError.Allowed:
            self.process_exit_error(error)
        print(user)


if __name__ == "__main__":
    linea = sys.stdin.readline()
    args = linea.strip().split(" ")
    g = GvaGate(args)
    g.run()
