"""Persistence helpers for Sentra artifacts."""

from __future__ import annotations

import json
import os
from pathlib import Path
from typing import Any

STATE_DIR_NAME = ".sentra"


def normalize_path(value: Path | str, *, field_name: str) -> Path:
    raw_value = str(value).strip()
    if not raw_value:
        raise ValueError(f"{field_name.capitalize()} cannot be empty.")
    expanded = Path(os.path.expanduser(os.path.expandvars(raw_value)))
    try:
        return expanded.resolve(strict=False)
    except OSError:
        return expanded.absolute()


def ensure_state_dir(base_path: Path) -> Path:
    state_dir = normalize_path(base_path, field_name="workspace") / STATE_DIR_NAME
    state_dir.mkdir(parents=True, exist_ok=True)
    return state_dir


def artifact_path(base_path: Path, name: str) -> Path:
    return ensure_state_dir(base_path) / f"{name}.json"


def resume_state_path(base_path: Path) -> Path:
    return ensure_state_dir(base_path) / "scan_state.json"


def cache_path(base_path: Path) -> Path:
    return ensure_state_dir(base_path) / "scan_cache.json"


def fingerprint_override_path(base_path: Path) -> Path:
    return ensure_state_dir(base_path) / "fingerprint_overrides.json"


def user_fingerprint_override_path(base_path: Path) -> Path:
    return ensure_state_dir(base_path) / "fingerprint_user_overrides.json"


def cve_feed_path(base_path: Path) -> Path:
    return ensure_state_dir(base_path) / "cve_feed.json"


def save_json(path: Path, payload: Any) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(payload, indent=2, sort_keys=True), encoding="utf-8")


def load_json(path: Path) -> Any:
    return json.loads(path.read_text(encoding="utf-8"))


def delete_file(path: Path) -> None:
    if path.exists():
        path.unlink()

