# Familiar - Self-Hosted AI Companion Platform
# Copyright (c) 2026 George Scott Foley
# ORCID: 0009-0006-4957-0540
# Email: Georgescottfoley@proton.me
# Licensed under the MIT License - see LICENSE file for details

"""
Intake history store — tracks all intake operations for audit and review.

Uses JSON file storage (consistent with other stores in the platform).
Thread-safe with atomic writes.
"""

import json
import logging
import os
import secrets
import threading
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional

logger = logging.getLogger(__name__)

_lock = threading.Lock()


def _data_dir() -> Path:
    try:
        from familiar.core.paths import DATA_DIR

        return DATA_DIR
    except ImportError:
        return Path.home() / ".familiar" / "data"


class IntakeHistory:
    """Thread-safe JSON store for intake history."""

    def __init__(self, data_file: Optional[Path] = None):
        self._file = data_file or (_data_dir() / "intake_history.json")
        self._ensure_file()

    def _ensure_file(self):
        if not self._file.exists():
            self._file.parent.mkdir(parents=True, exist_ok=True)
            self._write({"entries": [], "version": 1})

    def _read(self) -> dict:
        try:
            return json.loads(self._file.read_text(encoding="utf-8"))
        except Exception:
            return {"entries": [], "version": 1}

    def _write(self, data: dict):
        tmp = self._file.with_suffix(".tmp")
        tmp.write_text(json.dumps(data, indent=2, default=str), encoding="utf-8")
        os.replace(str(tmp), str(self._file))
        try:
            os.chmod(str(self._file), 0o600)
        except OSError:
            pass

    def record(
        self,
        source_file: str,
        content_type: str,
        confidence: float,
        method: str,
        destination: str,
        success: bool,
        summary: str,
        record_id: Optional[str] = None,
        extracted_fields: Optional[dict] = None,
        text_preview: Optional[str] = None,
    ) -> str:
        """Record an intake operation. Returns entry ID."""
        entry_id = f"intake_{secrets.token_hex(6)}"
        entry = {
            "id": entry_id,
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "source_file": source_file,
            "content_type": content_type,
            "confidence": confidence,
            "method": method,
            "destination": destination,
            "success": success,
            "summary": summary,
            "record_id": record_id,
            "extracted_fields": extracted_fields or {},
            "text_preview": (text_preview or "")[:500],
        }

        with _lock:
            data = self._read()
            data["entries"].insert(0, entry)
            # Cap at 1000 entries
            data["entries"] = data["entries"][:1000]
            self._write(data)

        return entry_id

    def list_entries(
        self,
        limit: int = 50,
        content_type: Optional[str] = None,
        success_only: bool = False,
    ) -> list[dict]:
        """List intake history entries with optional filtering."""
        data = self._read()
        entries = data.get("entries", [])

        if content_type:
            entries = [e for e in entries if e.get("content_type") == content_type]
        if success_only:
            entries = [e for e in entries if e.get("success")]

        return entries[:limit]

    def get_entry(self, entry_id: str) -> Optional[dict]:
        """Get a specific intake entry by ID."""
        data = self._read()
        for entry in data.get("entries", []):
            if entry.get("id") == entry_id:
                return entry
        return None

    def get_stats(self) -> dict:
        """Get intake statistics."""
        data = self._read()
        entries = data.get("entries", [])

        if not entries:
            return {"total": 0, "success_rate": 0.0, "by_type": {}, "by_destination": {}}

        total = len(entries)
        successes = sum(1 for e in entries if e.get("success"))
        by_type: dict[str, int] = {}
        by_dest: dict[str, int] = {}

        for e in entries:
            ct = e.get("content_type", "unknown")
            by_type[ct] = by_type.get(ct, 0) + 1
            dest = e.get("destination", "unknown")
            by_dest[dest] = by_dest.get(dest, 0) + 1

        return {
            "total": total,
            "success_rate": round(successes / total, 2) if total else 0.0,
            "by_type": by_type,
            "by_destination": by_dest,
        }

    def clear(self):
        """Clear all history entries."""
        with _lock:
            self._write({"entries": [], "version": 1})


_instance: Optional[IntakeHistory] = None


def get_intake_history() -> IntakeHistory:
    """Singleton accessor."""
    global _instance
    if _instance is None:
        _instance = IntakeHistory()
    return _instance
