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

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

import argparse
import inspect
import os
import sys

from daemonize import Daemonize

from fenrirscreenreader import fenrirVersion
from fenrirscreenreader.core import fenrirManager

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


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.code_name}',
        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)'
    )
    argumentParser.add_argument(
        '-F',
        '--force-all-screens',
        action='store_true',
        help='Force Fenrir to respond on all screens, ignoring ignoreScreen setting')
    argumentParser.add_argument(
        '-i', '-I', '--ignore-screen',
        metavar='SCREEN',
        action='append',
        help='Ignore specific screen(s). Can be used multiple times. Same as ignoreScreen setting.'
    )
    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 = None
    try:
        fenrirApp = fenrirManager.FenrirManager(cliArgs)
        fenrirApp.proceed()
    except Exception as e:
        print(f"Error starting Fenrir: {e}", file=sys.stderr)
        if fenrirApp and hasattr(fenrirApp, 'cleanup_on_error'):
            try:
                fenrirApp.cleanup_on_error()
            except Exception as cleanup_error:
                print(
                    f"Error during cleanup: {cleanup_error}", file=sys.stderr)
        sys.exit(1)
    finally:
        if fenrirApp:
            del fenrirApp
        # Clean up PID file if it exists
        pidFile = "/run/fenrir.pid"
        if os.path.exists(pidFile):
            try:
                os.remove(pidFile)
            except Exception:
                pass


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()
