#!/usr/bin/env python3
"""Tests for Decision artifacts (Layer 1: Causal Memory)."""

import json
import sys
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory

# Add project root to path
sys.path.insert(0, str(Path(__file__).parent.parent))

from tools.util import calculate_hash
from tools.sentinel import NovyxSentinel


def _sample_decision():
    """Return a minimal, schema-compliant Decision artifact dict (without hash)."""
    timestamp = "2025-01-01T00:00:00+00:00"
    return {
        "@context": {
            "@vocab": "https://schema.org/",
            "novyx": "https://novyx.ai/ns/core#"
        },
        "@type": ["Decision", "DigitalDocument"],
        "uuid": "urn:uuid:12345678-1234-5678-1234-567812345678",
        "id": "urn:uuid:12345678-1234-5678-1234-567812345678",
        "name": "Pick Vector DB",
        "title": "Pick Vector DB",
        "articleBody": "Choose the initial vector database for v1.",
        "context": "Need a vector store that is fast, durable, and OSS-friendly.",
        "createdAt": timestamp,
        "updatedAt": timestamp,
        "options_considered": ["Qdrant", "Weaviate", "Pinecone"],
        "chosen_option": "Qdrant",
        "reasoning": "Best balance of performance, OSS, and local-first deployment.",
        "constraints": ["Must run locally", "Budget friendly"],
        "assumptions": ["Initial dataset <10M vectors"],
        "confidence": 0.72,
        "expected_outcome": "Stable vector search with low latency for MVP.",
        "category": "decisions",
        "novyx:ingestedAt": timestamp,
        "novyx:updatedAt": timestamp,
        "novyx:embedding": [],
        "novyx:semanticLinks": [],
        "sameAs": ["https://github.com/novyxlabs"],
        "novyx:integrityHash": "pending",
        "Integrity_Hash": "pending"
    }


class TestDecisionArtifacts(unittest.TestCase):
    """Decision artifact hashing and Sentinel validation."""

    def test_decision_hash_round_trip(self):
        """Hash computed on saved file matches stored value."""
        decision = _sample_decision()

        with TemporaryDirectory() as tmpdir:
            path = Path(tmpdir) / "decision.jsonld"
            path.write_text(json.dumps(decision, indent=2))

            digest = calculate_hash(path)
            decision["novyx:integrityHash"] = digest
            decision["Integrity_Hash"] = digest
            path.write_text(json.dumps(decision, indent=2))

            recalculated = calculate_hash(path)
            self.assertEqual(digest, recalculated)

    def test_sentinel_validates_decision_file(self):
        """Sentinel marks a compliant Decision artifact as passing."""
        decision = _sample_decision()

        with TemporaryDirectory() as tmpdir:
            path = Path(tmpdir) / "decision.jsonld"
            path.write_text(json.dumps(decision, indent=2))

            digest = calculate_hash(path)
            decision["novyx:integrityHash"] = digest
            decision["Integrity_Hash"] = digest
            path.write_text(json.dumps(decision, indent=2))

            sentinel = NovyxSentinel(root_dir=Path(tmpdir), verbose=False)
            sentinel.scan_directory(Path(tmpdir))
            self.assertTrue(sentinel.results)
            self.assertTrue(sentinel.results[0].passed)


if __name__ == "__main__":
    unittest.main()
