"""Smoke tests for GreyMatter Solo installation.

Cycle 21-22/40: Validates that all core modules import correctly
and basic operations work without external services.
"""
import pytest

_has_sqlite_vec = True
try:
    import sqlite_vec  # noqa: F401
except ImportError:
    _has_sqlite_vec = False


class TestCoreImports:
    """All core modules should import without errors."""

    def test_db_imports(self):
        from greymatter_core.db import Database, SQLiteDatabase
        assert Database is not None

    def test_config_imports(self):
        from greymatter_core.config import Config, load_config
        assert Config is not None

    def test_knowledge_imports(self):
        from greymatter_core.knowledge import KnowledgeStore, ENTRY_TYPES
        assert "pattern" in ENTRY_TYPES

    def test_patterns_imports(self):
        from greymatter_core.patterns import PatternManager
        assert PatternManager is not None

    def test_scanner_imports(self):
        from greymatter_core.scanner import SecretScanner, ScannerConfig
        assert SecretScanner is not None

    def test_policy_imports(self):
        from greymatter_core.policy import PolicyEngine, PolicyRule
        assert PolicyEngine is not None

    def test_quality_imports(self):
        from greymatter_core.quality import QualityEngine, QualityReport
        assert QualityEngine is not None

    def test_export_imports(self):
        from greymatter_core.export import KnowledgeExporter, KnowledgeImporter
        assert KnowledgeExporter is not None

    def test_soul_imports(self):
        from greymatter_core.soul import SoulManager
        assert SoulManager is not None

    def test_work_items_imports(self):
        from greymatter_core.work_items import WorkItemManager
        assert WorkItemManager is not None


@pytest.mark.skipif(not _has_sqlite_vec, reason="sqlite_vec not installed")
class TestBasicOperations:
    """Core operations work without external services."""

    def test_db_create_and_query(self, tmp_path):
        from greymatter_core.db import SQLiteDatabase
        db = SQLiteDatabase(str(tmp_path / "smoke.db"))
        # Tables should exist after init
        tables = db._conn.execute(
            "SELECT name FROM sqlite_master WHERE type='table'"
        ).fetchall()
        table_names = {t[0] for t in tables}
        assert "observations" in table_names
        assert "knowledge_entries" in table_names

    def test_knowledge_crud(self, tmp_path):
        from greymatter_core.db import SQLiteDatabase
        from greymatter_core.knowledge import KnowledgeStore

        db = SQLiteDatabase(str(tmp_path / "smoke.db"))
        ks = KnowledgeStore(db)

        entry = ks.create(
            entry_type="pattern",
            title="Smoke test entry",
            content="This is a smoke test",
        )
        assert entry["title"] == "Smoke test entry"

        found = ks.get(entry["id"])
        assert found is not None
        assert found["content"] == "This is a smoke test"

        results = ks.search(text="smoke")
        assert len(results) >= 1

    def test_scanner_scan_and_redact(self):
        from greymatter_core.scanner import SecretScanner

        scanner = SecretScanner()
        # Should detect AWS key
        detections = scanner.scan("AKIAIOSFODNN7EXAMPLE")
        assert len(detections) >= 1

        # Should redact
        redacted = scanner.redact("key=AKIAIOSFODNN7EXAMPLE")
        assert "AKIAIOSFODNN7EXAMPLE" not in redacted

    def test_quality_on_empty_db(self, tmp_path):
        from greymatter_core.db import SQLiteDatabase
        from greymatter_core.quality import QualityEngine

        db = SQLiteDatabase(str(tmp_path / "smoke.db"))
        qe = QualityEngine(db)
        report = qe.full_check()
        assert report.score == 1.0

    def test_export_empty_db(self, tmp_path):
        from greymatter_core.db import SQLiteDatabase
        from greymatter_core.export import KnowledgeExporter

        db = SQLiteDatabase(str(tmp_path / "smoke.db"))
        exporter = KnowledgeExporter(db)
        data = exporter.to_json()
        assert data["format"] == "greymatter-export"
        assert data["counts"]["knowledge_entries"] == 0

    def test_policy_evaluate(self):
        from greymatter_core.policy import (
            PolicyEngine, PolicyRule, PolicyOutcome,
            Condition, EvalContext,
        )

        engine = PolicyEngine([
            PolicyRule(
                rule_id="test",
                description="Test rule",
                outcome=PolicyOutcome.ALLOW,
                priority=100,
            ),
        ])
        ctx = EvalContext(content="hello")
        decision = engine.evaluate(ctx)
        assert decision.outcome == PolicyOutcome.ALLOW


class TestCLIImports:
    """CLI should import without external services."""

    def test_cli_app_imports(self):
        from greymatter_cli.main import app
        assert app is not None

    def test_cli_version(self):
        from greymatter_cli.main import VERSION
        assert VERSION is not None
        assert len(VERSION) >= 5  # e.g., "1.1.0"


class TestPluginImports:
    """Plugin should import cleanly."""

    def test_server_module_imports(self):
        import greymatter_plugin.server
        assert hasattr(greymatter_plugin.server, "create_app")


class TestNewModuleImports:
    """v1.3.0 modules should import."""

    def test_code_module_imports(self):
        from greymatter_code.db import CodeDB
        from greymatter_code.models import CodeSymbol, SymbolLink
        assert CodeDB is not None

    def test_code_registry_imports(self):
        from greymatter_code.registry import LanguageRegistry
        assert LanguageRegistry is not None

    def test_cluster_state_imports(self):
        from greymatter_core.cluster.state import NodeStateMachine, NodeState
        assert NodeState.SOLO is not None

    def test_cluster_health_imports(self):
        from greymatter_core.cluster.health import HealthChecker, HealthStatus
        assert HealthStatus.HEALTHY is not None

    def test_cluster_discovery_imports(self):
        from greymatter_core.cluster.discovery import ClusterEndpoint
        assert ClusterEndpoint is not None

    def test_sync_models_imports(self):
        from greymatter_core.sync.models import SyncResult, SyncState
        assert SyncResult is not None

    def test_export_imports(self):
        from greymatter_core.export import KnowledgeExporter, KnowledgeImporter
        assert KnowledgeExporter is not None
