import json
import os

class ConfigManager:
    def __init__(self, config_path='cgminer.conf'):
        self.config_path = config_path

    def load_config(self):
        if not os.path.exists(self.config_path):
            return self.get_default_config()
        try:
            with open(self.config_path, 'r') as f:
                return json.load(f)
        except:
            return self.get_default_config()

    def save_config(self, config_data):
        try:
            # Validate numeric fields
            if 'freq' in config_data:
                config_data['freq'] = int(config_data['freq'])
                
            with open(self.config_path, 'w') as f:
                json.dump(config_data, f, indent=4)
            return True
        except Exception as e:
            print(f"Error saving config: {e}")
            return False

    def get_default_config(self):
        return {
            "pools": [
                {
                    "url": "stratum+tcp://solo.ckpool.org:3333",
                    "user": "144N35t62x8qC21eQ8qW2q2q2q2q2q2q2q",
                    "pass": "x"
                }
            ],
            "api-listen": True,
            "api-allow": "W:127.0.0.1",
            "gridseed-options": "freq=850,chips=5",
            "freq": "850" 
        }
