"""
Settings Service - Manages global application settings
"""
from models.Settings import Settings
from database.database import db

def get_setting(key, default=None):
    """Get a setting value by key"""
    setting = Settings.query.filter_by(key=key).first()
    return setting.value if setting else default

def set_setting(key, value, description=None):
    """Set a setting value"""
    setting = Settings.query.filter_by(key=key).first()
    if setting:
        setting.value = value
        if description:
            setting.description = description
    else:
        setting = Settings(key=key, value=value, description=description)
        db.session.add(setting)
    
    db.session.commit()
    return setting

def get_all_settings():
    """Get all settings as a dictionary"""
    settings = Settings.query.all()
    return {s.key: s.value for s in settings}

def get_all_settings_detailed():
    """Get all settings with full details"""
    settings = Settings.query.all()
    return [s.to_dict() for s in settings]

def initialize_default_settings():
    """Initialize default settings if they don't exist"""
    defaults = {
        'labelstudio_api_url': {
            'value': 'http://192.168.1.19:8080/api',
            'description': 'Label Studio API URL'
        },
        'labelstudio_api_token': {
            'value': 'c1cef980b7c73004f4ee880a42839313b863869f',
            'description': 'Label Studio API Token'
        },
        'yolox_path': {
            'value': 'C:/YOLOX',
            'description': 'Path to YOLOX installation directory'
        },
        'yolox_venv_path': {
            'value': '/home/kitraining/Yolox/yolox_venv/bin/activate',
            'description': 'Path to YOLOX virtual environment activation script'
        },
        'yolox_output_path': {
            'value': './backend',
            'description': 'Output folder for YOLOX experiment files and JSONs'
        },
        'yolox_data_dir': {
            'value': '/home/kitraining/To_Annotate/',
            'description': 'Data directory path for YOLOX training (where images are located)'
        }
    }
    
    for key, data in defaults.items():
        existing = Settings.query.filter_by(key=key).first()
        if not existing:
            setting = Settings(key=key, value=data['value'], description=data['description'])
            db.session.add(setting)
    
    db.session.commit()
