# -*- coding: utf-8 -*-
"""yjm_settings.py

Host 설정 저장/로드 모듈.

현재는 Google Drive API 직접 업로드가 아니라, Google Drive for Desktop 같은
동기화 폴더 또는 일반 로컬 폴더에 snapshot ring 파일을 저장한다.
해당 폴더가 Google Drive 동기화 폴더이면 Drive 클라이언트가 클라우드 업로드를 담당한다.
"""
from __future__ import annotations

import json
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any


@dataclass
class SnapshotSettings:
    enabled: bool = False
    folder: str = "snapshots_drive"
    keep_count: int = 10
    interval_sec: float = 1.0
    min_save_interval_sec: float = 3.0
    change_threshold_percent: float = 2.0
    max_width: int = 1280
    jpeg_quality: int = 72


@dataclass
class UiSettings:
    window_geometry: str = "940x850"
    window_state: str = "normal"
    source: str = "desktop"
    display_index: int = 0
    lock_window: bool = False
    remote_control: bool = True
    file_transfer: bool = False
    clipboard: bool = False
    fps: int = 12
    jpeg_quality: int = 70
    max_width: int = 1280
    draw_border: bool = True


@dataclass
class AppSettings:
    ui: UiSettings = field(default_factory=UiSettings)
    snapshot: SnapshotSettings = field(default_factory=SnapshotSettings)


def _merge_dataclass(instance: Any, values: dict[str, Any]) -> Any:
    for key, value in values.items():
        if not hasattr(instance, key):
            continue
        current = getattr(instance, key)
        if hasattr(current, "__dataclass_fields__") and isinstance(value, dict):
            _merge_dataclass(current, value)
        else:
            setattr(instance, key, value)
    return instance


def load_settings(path: str | Path) -> AppSettings:
    path = Path(path)
    settings = AppSettings()
    if not path.exists():
        return settings
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
        if isinstance(data, dict):
            _merge_dataclass(settings, data)
    except Exception:
        # 설정 파일 오류는 프로그램 실행을 막지 않는다.
        return AppSettings()
    return settings


def save_settings(path: str | Path, settings: AppSettings) -> None:
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(asdict(settings), ensure_ascii=False, indent=2), encoding="utf-8")
