#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Fenrir TTY screen reader
# By Chrys, Storm Dragon, and contributors.

import os
import sys
import inspect
import argparse
from daemonize import Daemonize

# Get the fenrir installation path
fenrirPath = os.path.dirname(os.path.realpath(os.path.abspath(inspect.getfile(inspect.currentframe()))))
if not fenrirPath in sys.path:
    sys.path.append(fenrirPath)

from fenrirscreenreader.core import fenrirManager
from fenrirscreenreader import fenrirVersion

def create_argument_parser():
    """Create and return the argument parser for Fenrir"""
    argumentParser = argparse.ArgumentParser(
        description="Fenrir - A console screen reader for Linux",
        formatter_class=argparse.RawDescriptionHelpFormatter
    )
    argumentParser.add_argument(
        '-v', '--version',
        action='version',
        version=f'Fenrir screen reader version {fenrirVersion.version}-{fenrirVersion.codeName}',
        help='Show version information and exit'
    )
    argumentParser.add_argument(
        '-f', '--foreground',
        action='store_true',
        help='Run Fenrir in the foreground (default: run as daemon)'
    )
    argumentParser.add_argument(
        '-s', '--setting',
        metavar='SETTING-FILE',
        default='/etc/fenrir/settings/settings.conf',
        help='Path to custom settings file'
    )
    argumentParser.add_argument(
        '-o', '--options',
        metavar='SECTION#SETTING=VALUE;..',
        default='',
        help='Override settings file options. Format: SECTION#SETTING=VALUE;... (case sensitive)'
    )
    argumentParser.add_argument(
        '-d', '--debug',
        action='store_true',
        help='Enable debug mode'
    )
    argumentParser.add_argument(
        '-p', '--print',
        action='store_true',
        help='Print debug messages to screen'
    )
    argumentParser.add_argument(
        '-e', '--emulated-pty',
        action='store_true',
        help='Use PTY emulation with escape sequences for input (enables desktop/X/Wayland usage)'
    )
    argumentParser.add_argument(
        '-E', '--emulated-evdev',
        action='store_true',
        help='Use PTY emulation with evdev for input (single instance)'
    )
    return argumentParser

def validate_arguments(cliArgs):
    """Validate command line arguments"""
    if cliArgs.options:
        for option in cliArgs.options.split(';'):
            if option and ('#' not in option or '=' not in option):
                return False, f"Invalid option format: {option}\nExpected format: SECTION#SETTING=VALUE"
    
    if cliArgs.emulated_pty and cliArgs.emulated_evdev:
        return False, "Cannot use both --emulated-pty and --emulated-evdev simultaneously"
    
    return True, None

def run_fenrir():
    """Main function that runs Fenrir"""
    fenrirApp = fenrirManager.fenrirManager(cliArgs)
    fenrirApp.proceed()
    del fenrirApp

def main():
    global cliArgs
    argumentParser = create_argument_parser()
    cliArgs = argumentParser.parse_args()
    
    # Validate arguments
    isValid, errorMsg = validate_arguments(cliArgs)
    if not isValid:
        argumentParser.error(errorMsg)
        sys.exit(1)

    if cliArgs.foreground or cliArgs.emulated_pty:
        # Run directly in foreground
        run_fenrir()
    else:
        # Run as daemon
        pidFile = "/run/fenrir.pid"
        daemonProcess = Daemonize(
            app="fenrir",
            pid=pidFile,
            action=run_fenrir,
            chdir=fenrirPath
        )
        daemonProcess.start()

if __name__ == "__main__":
    main()
