"""GDPR/CCPA compliance framework — data processing consent, right-to-delete, audit log."""

from __future__ import annotations
import json, hashlib, time
from pathlib import Path
from typing import Optional

class DataConsent:
    def __init__(self, store_dir: Optional[Path] = None):
        self._dir = store_dir or Path("data/compliance")
        self._dir.mkdir(parents=True, exist_ok=True)

    def record_consent(self, user_id: str, purposes: list[str], ip_hash: str = "") -> dict:
        record = {"user_id": user_id, "purposes": purposes, "ip_hash": ip_hash,
                  "consented_at": time.time(), "version": "1.0"}
        f = self._dir / f"consent_{hashlib.md5(user_id.encode()).hexdigest()[:12]}.json"
        f.write_text(json.dumps(record, indent=2), encoding="utf-8")
        return record

    def check_consent(self, user_id: str, purpose: str) -> bool:
        f = self._dir / f"consent_{hashlib.md5(user_id.encode()).hexdigest()[:12]}.json"
        if not f.exists(): return False
        try:
            record = json.loads(f.read_text(encoding="utf-8"))
            return purpose in record.get("purposes", [])
        except Exception:
            return False

    def revoke_consent(self, user_id: str) -> bool:
        f = self._dir / f"consent_{hashlib.md5(user_id.encode()).hexdigest()[:12]}.json"
        if f.exists():
            f.unlink()
            return True
        return False

    def delete_user_data(self, user_id: str) -> dict:
        """Right-to-delete: removes all user data files."""
        deleted = []
        uid_hash = hashlib.md5(user_id.encode()).hexdigest()[:12]
        for fp in self._dir.glob(f"*{uid_hash}*"):
            fp.unlink()
            deleted.append(fp.name)
        return {"user_id": user_id, "deleted_files": len(deleted), "timestamp": time.time()}

    def audit_log(self, action: str, user_id: str, details: str = "") -> None:
        log_file = self._dir / "audit.ndjson"
        entry = json.dumps({"ts": time.time(), "action": action, "user_id": user_id, "details": details})
        with open(log_file, "a", encoding="utf-8") as f:
            f.write(entry + "\n")
