"""
Carrier image reuse tracking.

Tracks SHA-256 hashes of images used as carriers for steganographic
encoding. Warns when a carrier is reused, since comparing two versions
of the same carrier can trivially reveal steganographic modification.
"""

from __future__ import annotations

import hashlib
import json
from datetime import UTC, datetime
from pathlib import Path


class CarrierTracker:
    """Tracks carrier image usage to warn on reuse."""

    def __init__(self, db_path: Path | None = None):
        from soosef.paths import BASE_DIR

        self._db_path = db_path or (BASE_DIR / "carrier_history.json")

    def _load(self) -> dict[str, dict]:
        if self._db_path.exists():
            return json.loads(self._db_path.read_text())
        return {}

    def _save(self, data: dict) -> None:
        self._db_path.parent.mkdir(parents=True, exist_ok=True)
        self._db_path.write_text(json.dumps(data))

    def record_use(self, carrier_data: bytes, filename: str = "") -> str | None:
        """Record a carrier image use. Returns warning message if reused, None otherwise."""
        sha256 = hashlib.sha256(carrier_data).hexdigest()
        history = self._load()

        if sha256 in history:
            prev = history[sha256]
            prev_date = prev.get("last_used", "unknown date")
            prev_count = prev.get("count", 1)
            # Update
            history[sha256]["count"] = prev_count + 1
            history[sha256]["last_used"] = datetime.now(UTC).isoformat()
            self._save(history)
            return (
                f"WARNING: This carrier image was previously used for encoding "
                f"on {prev_date[:10]} ({prev_count} previous use(s)). "
                f"Reusing carriers weakens steganographic security — "
                f"an adversary can compare versions to detect hidden data."
            )

        history[sha256] = {
            "first_used": datetime.now(UTC).isoformat(),
            "last_used": datetime.now(UTC).isoformat(),
            "count": 1,
            "filename": filename,
        }
        self._save(history)
        return None

    def check(self, carrier_data: bytes) -> bool:
        """Check if a carrier has been used before (without recording)."""
        sha256 = hashlib.sha256(carrier_data).hexdigest()
        return sha256 in self._load()
