import os
import logging
from datetime import datetime
from pathlib import Path
from typing import Optional


def setup_logger(logs_dir: Optional[str] = None, quality: int = 90) -> logging.Logger:
    if logs_dir is None:
        logs_dir = Path(__file__).parent.parent / "logs"
    else:
        logs_dir = Path(logs_dir)
    
    logs_dir.mkdir(parents=True, exist_ok=True)
    
    today = datetime.now().strftime("%Y-%m-%d")
    log_filename = f"resize_webp_q{quality}_{today}.log"
    log_path = logs_dir / log_filename
    
    logger = logging.getLogger("PhotoResizer")
    logger.setLevel(logging.INFO)
    
    if logger.handlers:
        logger.handlers.clear()
    
    file_handler = logging.FileHandler(log_path, encoding='utf-8')
    file_handler.setLevel(logging.INFO)
    
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)
    
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    file_handler.setFormatter(formatter)
    console_handler.setFormatter(formatter)
    
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)
    
    return logger


def log_start(logger: logging.Logger, input_path: Path, output_path: Path, quality: int, total_files: int):
    logger.info("=" * 50)
    logger.info("PhotoResizer v1.0 시작")
    logger.info("=" * 50)
    logger.info(f"입력 폴더: {input_path}")
    logger.info(f"출력 폴더: {output_path}")
    logger.info(f"화질: {quality}")
    logger.info(f"총 파일 수: {total_files}")
    logger.info("-" * 50)


def log_progress(logger: logging.Logger, current: int, total: int, filename: str):
    percent = (current / total * 100) if total > 0 else 0
    bar_length = 40
    filled = int(bar_length * current / total) if total > 0 else 0
    bar = '#' * filled + '-' * (bar_length - filled)
    logger.info(f"[{bar}] {percent:.1f}% ({current}/{total}) - {filename}")


def log_success(logger: logging.Logger, source_file: str, output_file: str):
    logger.info(f"성공: {source_file} -> {output_file}")


def log_error(logger: logging.Logger, source_file: str, error_msg: str):
    logger.error(f"실패: {source_file} - {error_msg}")


def log_complete(logger: logging.Logger, success_count: int, fail_count: int, elapsed_time: float):
    logger.info("=" * 50)
    logger.info("처리 완료")
    logger.info(f"성공: {success_count}개")
    logger.info(f"실패: {fail_count}개")
    logger.info(f"소요 시간: {elapsed_time:.2f}초")
    logger.info("=" * 50)