import json
import os
from pathlib import Path
from typing import Dict, Any, Optional

DEFAULT_CONFIG = {
    "project": "PhotoResizer",
    "version": "1.0.0",
    "created_at": "2026-07-06",
    "input_folder": "source",
    "output_format": "webp",
    "output_quality": 90,
    "max_size": 1920,
    "test_mode": False,
    "test_count": 10,
    "supported_extensions": [".jpg", ".jpeg", ".png", ".webp"],
    "remove_exif": True,
    "overwrite_output": False
}


def load_config(config_path: Optional[str] = None) -> Dict[str, Any]:
    if config_path is None:
        config_path = Path(__file__).parent.parent / "config.json"
    else:
        config_path = Path(config_path)
    
    if not config_path.exists():
        return DEFAULT_CONFIG.copy()
    
    try:
        with open(config_path, 'r', encoding='utf-8') as f:
            config = json.load(f)
        
        for key, value in DEFAULT_CONFIG.items():
            if key not in config:
                config[key] = value
        
        return config
    except (json.JSONDecodeError, IOError):
        return DEFAULT_CONFIG.copy()


def get_input_path(config: Dict[str, Any]) -> Path:
    input_folder = config.get("input_folder", "source")
    if os.path.isabs(input_folder):
        return Path(input_folder)
    return Path(__file__).parent.parent / input_folder


def get_output_folder_name(source_path: Path, quality: int) -> str:
    return f"{source_path.name}_webp_q{quality}"


def get_output_path(source_path: Path, quality: int) -> Path:
    output_folder_name = get_output_folder_name(source_path, quality)
    return source_path.parent / output_folder_name


def get_unique_output_path(source_path: Path, quality: int) -> Path:
    base_name = get_output_folder_name(source_path, quality)
    parent = source_path.parent
    candidate = parent / base_name
    counter = 1
    while candidate.exists():
        candidate = parent / f"{base_name}_{counter}"
        counter += 1
    return candidate