import json
import os
from pathlib import Path

class PrintConfigManager:
    CONFIG_FILENAME = 'printer_config.json'
    DEFAULT_CONFIG = {
        'label_printer': {'ip': '192.168.9.221', 'port': 9100},
        'network_printer': {'ip': '192.168.9.250', 'port': 9100}
    }

    @classmethod
    def _get_config_path(cls):
        # Determine the path relative to this file's directory
        current_dir = Path(__file__).parent
        return current_dir / cls.CONFIG_FILENAME

    @classmethod
    def get_config(cls, printer_type='label_printer'):
        """
        Retrieve configuration for a given printer type.
        Returns a dict with 'ip' and 'port'.
        """
        config_path = cls._get_config_path()
        if not config_path.exists():
            # Write default config if not exists
            cls.save_config(cls.DEFAULT_CONFIG)
            config = cls.DEFAULT_CONFIG
        else:
            try:
                with open(config_path, 'r', encoding='utf-8') as f:
                    config = json.load(f)
            except Exception as e:
                print(f"Error reading printer config: {e}")
                config = cls.DEFAULT_CONFIG
        # Return specific printer config, falling back to default for that type
        printer_config = config.get(printer_type, cls.DEFAULT_CONFIG.get(printer_type))
        # Ensure it's a dict with ip and port
        if not printer_config or 'ip' not in printer_config:
            printer_config = cls.DEFAULT_CONFIG.get(printer_type, {'ip': '127.0.0.1', 'port': 9100})
        return printer_config

    @classmethod
    def save_config(cls, new_config):
        """
        Save entire config dictionary to file.
        new_config should be a dict with keys 'label_printer' and/or 'network_printer'.
        """
        config_path = cls._get_config_path()
        try:
            # If file exists, merge existing with new
            existing = {}
            if config_path.exists():
                with open(config_path, 'r', encoding='utf-8') as f:
                    existing = json.load(f)
            existing.update(new_config)
            with open(config_path, 'w', encoding='utf-8') as f:
                json.dump(existing, f, indent=2)
        except Exception as e:
            print(f"Error saving printer config: {e}")
            raise
