# ws_package/utils/tracker_status.py
"""
Utility to manage persistent tracker status (start/stop) from WebSocket commands.
"""

import configparser
from pathlib import Path
from ws_package.log.writer import LogWriter
from importlib.resources import files, as_file

logger = LogWriter.file(__name__)

TRACKER_STATUS_SECTION = 'Tracker'
TRACKER_STATUS_KEY = 'tracker_status'
DEFAULT_STATUS = 'start'

# Resolve config file path - works in both dev and PyInstaller frozen apps
def _get_config_file():
    """Get the config file path as a string."""
    config_resource = files('ws_package').joinpath("config.ini")
    with as_file(config_resource) as config_path:
        return str(config_path)

CONFIG_FILE = _get_config_file()


def get_tracker_status() -> str:
    """
    Get the current tracker status from config file.
    
    Returns:
        str: 'start' or 'stop', defaults to 'start'
    """
    try:
        config = configparser.ConfigParser()
        config.read(CONFIG_FILE)
        
        if config.has_section(TRACKER_STATUS_SECTION):
            status = config.get(TRACKER_STATUS_SECTION, TRACKER_STATUS_KEY, fallback=DEFAULT_STATUS)
            return status.lower().strip()
        else:
            # Section doesn't exist, create it with default
            set_tracker_status(DEFAULT_STATUS)
            return DEFAULT_STATUS
    except Exception as e:
        logger.error("Error reading tracker status: %s", e)
        return DEFAULT_STATUS


def set_tracker_status(status: str) -> bool:
    """
    Set the tracker status in config file.
    
    Args:
        status: 'start' or 'stop'
        
    Returns:
        bool: True if successful, False otherwise
    """
    try:
        # Validate status
        status = status.lower().strip()
        if status not in ['start', 'stop']:
            logger.error("Invalid tracker status: %s, must be 'start' or 'stop'", status)
            return False
        
        config = configparser.ConfigParser()
        config.read(CONFIG_FILE)
        
        # Create section if it doesn't exist
        if not config.has_section(TRACKER_STATUS_SECTION):
            config.add_section(TRACKER_STATUS_SECTION)
        
        # Set the status
        config.set(TRACKER_STATUS_SECTION, TRACKER_STATUS_KEY, status)
        
        # Write to file
        with open(CONFIG_FILE, 'w') as config_file:
            config.write(config_file)
        
        logger.info("Tracker status saved: %s", status)
        return True
        
    except Exception as e:
        logger.error("Error saving tracker status: %s", e)
        return False


def is_tracking_enabled() -> bool:
    """
    Check if tracking is enabled (status is 'start').
    
    Returns:
        bool: True if tracking is enabled, False if disabled
    """
    status = get_tracker_status()
    return status == 'start'

