import importlib
import json
from datetime import datetime, timedelta, timezone
from pathlib import Path

import pytest


context = importlib.import_module("gjalla_precommit.config.context")


def test_load_context_from_cache(home_dir: Path, sample_context: dict):
    cache_path = context.save_context("project-123", sample_context)
    loaded = context.load_context("project-123")
    assert loaded == json.loads(cache_path.read_text(encoding="utf-8"))


def test_load_context_cache_miss(home_dir: Path):
    assert context.load_context("missing") is None


def test_save_context_to_cache(home_dir: Path, sample_context: dict):
    cache_path = context.save_context("project-123", sample_context)
    assert cache_path.exists()


def test_context_hash_computed(sample_context: dict):
    digest = context.compute_context_hash(sample_context)
    assert isinstance(digest, str)
    assert len(digest) >= 16


def test_context_freshness_check_fresh(sample_context: dict):
    recent = dict(sample_context)
    recent["fetched_at"] = datetime.now(timezone.utc).isoformat()
    assert context.is_context_fresh(recent, max_age_hours=24)


def test_context_freshness_check_stale(sample_context: dict):
    stale = dict(sample_context)
    stale["fetched_at"] = (datetime.now(timezone.utc) - timedelta(hours=25)).isoformat()
    assert not context.is_context_fresh(stale, max_age_hours=24)


def test_context_refresh_fetches_from_api(monkeypatch, home_dir: Path, sample_context: dict):
    refreshed = dict(sample_context)
    refreshed["context_hash"] = "newhash"

    async def _fake_fetch(_project_id):
        return refreshed

    monkeypatch.setattr(context, "fetch_context_from_api", _fake_fetch)
    result = context.refresh_context_if_stale("project-123", max_age_hours=0)
    assert result["context_hash"] == "newhash"


def test_context_includes_capabilities(sample_context: dict):
    assert isinstance(sample_context.get("capabilities"), list)


def test_context_includes_architecture(sample_context: dict):
    assert isinstance(sample_context.get("architecture"), dict)


def test_context_includes_rules(sample_context: dict):
    assert isinstance(sample_context.get("rules"), list)
