from __future__ import annotations

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

DEFAULT_SETTINGS: Dict[str, Any] = {
    "last_url": "https://tamerserbes.com",
    "check_links": True,
    "max_links": 20,
    "auto_save_reports": True,
    "mode": "single",
    "max_pages": 10,
    "use_sitemap": True,
}


def load_settings(path: str | Path) -> Dict[str, Any]:
    settings = DEFAULT_SETTINGS.copy()
    file_path = Path(path)
    if file_path.exists():
        try:
            loaded = json.loads(file_path.read_text(encoding="utf-8"))
            if isinstance(loaded, dict):
                settings.update({k: loaded[k] for k in DEFAULT_SETTINGS if k in loaded})
        except Exception:
            pass
    settings["max_links"] = max(1, min(int(settings.get("max_links") or 20), 100))
    settings["max_pages"] = max(1, min(int(settings.get("max_pages") or 10), 100))
    settings["mode"] = "site" if settings.get("mode") == "site" else "single"
    settings["check_links"] = bool(settings.get("check_links"))
    settings["auto_save_reports"] = bool(settings.get("auto_save_reports"))
    settings["use_sitemap"] = bool(settings.get("use_sitemap"))
    return settings


def save_settings(path: str | Path, settings: Dict[str, Any]) -> None:
    file_path = Path(path)
    file_path.parent.mkdir(parents=True, exist_ok=True)
    safe = DEFAULT_SETTINGS.copy()
    safe.update({k: settings.get(k, safe[k]) for k in DEFAULT_SETTINGS})
    safe["max_links"] = max(1, min(int(safe.get("max_links") or 20), 100))
    safe["max_pages"] = max(1, min(int(safe.get("max_pages") or 10), 100))
    safe["mode"] = "site" if safe.get("mode") == "site" else "single"
    file_path.write_text(json.dumps(safe, ensure_ascii=False, indent=2), encoding="utf-8")
