#!/usr/bin/env python3
import os
import traceback
import sys
import argparse


from common.utils  import read_csv
from common.utils  import dump_rows,dump_clean
from common.utils  import validate_values,validate_datastoreitemname
from common.repair import repair_listvalues,repair_values,normalize_objectclass,normalize_ldapsearch
from common.repair import collect_user_assignments,remove_tarantella,remove_mail
from common.repair import remove_tarantella_assignments,check_for_visulox


from group.utils   import process_hostgroup,process_appgroup
from profile.utils import process_profile
from host.utils    import process_host
from unix.utils    import process_unix
from vlx.utils     import process_vlx
from rdp.utils     import process_rdp

VARKEYS_OF_INTEREST = [
        "scottahints",
        "scottaarguments",
        "scottafilepath",
        "description",
        "sn",
        "scottadnsname",
        "scottamembersearch",
        "cn",
        "dn",
        ]
LISTKEYS_OF_INTEREST = [
        "datastoreitemname",
        "objectclass",
        "member",
        "roleoccupant",
        "scottawebtopcontents",
        "scottamemberusers",
        "scottamembergroups",
        "scottawebtopcontents-internalbacklink",
        "roleoccupant-internalbacklink",
        "scottahosts-internalbacklink",
        "scottahosts"
    ]

#see parser also
FLAGS = ["servers", "servergroups", "profiles", "appgroups", "vlx", "unix", "rdp"]

def parse_args():
    parser = argparse.ArgumentParser(
        description="Export Datastore for VLX5"
    )

    # Main switches
    parser.add_argument("-all", "--all", action="store_true", help="Export everything")
    parser.add_argument("-p", "--profiles", action="store_true", help="Profiles")
    parser.add_argument("-s", "--servers", action="store_true", help="Servers")
    parser.add_argument("-sg", "--servergroups", action="store_true", help="Server groups")
    parser.add_argument("-ag", "--appgroups", action="store_true", help="Application groups")

    parser.add_argument("-unix", action="store_true", help="Unix application")
    parser.add_argument("-vlx", action="store_true", help="VLX application")
    parser.add_argument("-rdp", action="store_true", help="RDP application")

    parser.add_argument("-debug", action="store_true", help="Debug")

    # Input file
    parser.add_argument("file", nargs="?", help="Input CSV file")

    return parser.parse_args()

def normalize_and_validate_flags(args, flags):
    # Apply -all
    if args.all:
        for flag in flags:
            setattr(args, flag, True)

    # Collect selected flags
    selected = [f for f in flags if getattr(args, f)]

    # Validate
    if not selected:
        raise ValueError("No valid option selected. Use -all or specific switches.")

    return selected

def resolve_input_file(file_arg):
    """
    Returns a valid file path.
    - If file_arg is given → check existence
    - If not → fallback to 'data.csv'
    """

    if file_arg:
        if not os.path.isfile(file_arg):
            raise FileNotFoundError(f"Input file not found: {file_arg}")
        return file_arg

    # fallback
    default_file = "data.csv"
    if not os.path.isfile(default_file):
        raise FileNotFoundError(
            "No input file provided and default 'data.csv' not found."
        )

    return default_file


def main():
    args = parse_args()
    try:
        selected_flags = normalize_and_validate_flags(args, FLAGS)
        input_file = resolve_input_file(args.file)

        # --- clean dump file ---
        dump_clean()
        # --- Load CSV data ---
        data = read_csv(input_file)

        # --- Preprocessing ---
        repair_listvalues(data, LISTKEYS_OF_INTEREST)
        repair_values(data, VARKEYS_OF_INTEREST)
        validate_values(data, LISTKEYS_OF_INTEREST)
        validate_datastoreitemname(data)
        normalize_objectclass(data)
        normalize_ldapsearch(data)
        remove_tarantella(data)
        remove_mail(data)
        remove_tarantella_assignments(data)
        check_for_visulox(data)

        dump_rows(data,"raw", "RAW DATA")

        # --- Processing ---
        if args.profiles:
            profiles=process_profile(data)
            dump_rows(profiles,"profiles", "PROFILES")

        if args.servers:
            hosts=process_host(data)
            dump_rows(hosts, "hosts", "HOSTS")

        if args.servergroups:
            hostgroups=process_hostgroup(data)
            dump_rows(hostgroups,"hostgroups", "HOSTGROUPS")

        if args.appgroups:
            appgroups=process_appgroup(data)
            dump_rows(appgroups,"appgroups", "APPLICATION GROUPS")

        # --- Additional filters (extend later) ---
        if args.unix:
            unix=process_unix(data)
            dump_rows(unix,"unixapps", "UNIX APPLICATIONS")

        if args.vlx:
            vlx=process_vlx(data)
            dump_rows(vlx, "vlxapps", "VISULOX APPLICATIONS")

        if args.rdp:
            rdp=process_rdp(data)
            dump_rows(rdp, "rdpapps", "RDP APPLICATIONS")

        if args.all:
            assignments=collect_user_assignments(appgroups+unix+vlx+rdp)
            dump_rows(assignments, "assignments", "User Assignments")


    except Exception as e:
        if getattr(args, "debug", False):
            traceback.print_exc()
        else:
            print(f"Error: {e}", file=sys.stderr)

        sys.exit(1)
if __name__ == "__main__":
    main()
