import sys
import time
from pathlib import Path

from config import load_config, get_input_path, get_unique_output_path
from image_scanner import scan_images
from image_processor import resize_image
from image_saver import save_image
from logger import setup_logger, log_start, log_progress, log_success, log_error, log_complete


def main():
    print("PhotoResizer v1.0")
    print("=" * 50)
    
    config = load_config()
    
    source_path = get_input_path(config)
    
    if not source_path.exists():
        print(f"[ERROR] 입력 폴더가 존재하지 않습니다: {source_path}")
        print("config.json의 input_folder를 확인하거나 source 폴더를 생성해주세요.")
        input("Press any key to continue...")
        return
    
    quality = config.get("output_quality", 90)
    max_size = config.get("max_size", 1920)
    test_mode = config.get("test_mode", False)
    test_count = config.get("test_count", 10)
    remove_exif = config.get("remove_exif", True)
    
    output_path = get_unique_output_path(source_path, quality)
    
    print(f"입력 폴더: {source_path}")
    print(f"출력 폴더: {output_path}")
    print(f"화질: {quality}")
    print(f"최대 크기: {max_size}px")
    print(f"테스트 모드: {'ON' if test_mode else 'OFF'}")
    print("=" * 50)
    
    logger = setup_logger(quality=quality)
    
    image_files = scan_images(config)
    
    if not image_files:
        print("[INFO] 처리할 이미지가 없습니다.")
        return
    
    if test_mode and len(image_files) > test_count:
        image_files = image_files[:test_count]
    
    total_files = len(image_files)
    log_start(logger, source_path, output_path, quality, total_files)
    
    print(f"\n이미지 검색 완료: {total_files}개")
    print("-" * 50)
    
    success_count = 0
    fail_count = 0
    errors = []
    
    start_time = time.time()
    
    for idx, image_file in enumerate(image_files, 1):
        try:
            log_progress(logger, idx, total_files, image_file.name)
            
            image_bytes = resize_image(image_file, max_size, quality, remove_exif)
            
            if image_bytes is None:
                fail_count += 1
                errors.append(str(image_file))
                log_error(logger, str(image_file), "이미지 처리 실패")
                continue
            
            saved, output_file = save_image(image_bytes, image_file, source_path, output_path, quality)
            
            if saved:
                success_count += 1
                log_success(logger, str(image_file), str(output_file))
            else:
                fail_count += 1
                errors.append(str(image_file))
                log_error(logger, str(image_file), "파일 저장 실패")
                
        except Exception as e:
            fail_count += 1
            errors.append(str(image_file))
            log_error(logger, str(image_file), str(e))
    
    elapsed_time = time.time() - start_time
    log_complete(logger, success_count, fail_count, elapsed_time)
    
    print("\n" + "=" * 50)
    print("처리 완료")
    print("=" * 50)
    print(f"입력 파일: {total_files}개")
    print(f"성공: {success_count}개")
    print(f"실패: {fail_count}개")
    print(f"출력 폴더: {output_path}")
    print(f"소요 시간: {elapsed_time:.2f}초")
    print("=" * 50)
    
    input("Press any key to continue...")


if __name__ == "__main__":
    main()