"""Tests for Persona Store feature."""

import os
import tempfile
from pathlib import Path

import pytest

from locidb.core.db import LociDB


@pytest.fixture
def db(tmp_path):
    loci = LociDB(path=tmp_path / "test.loci")
    yield loci
    loci.close()


class TestPersonaSetGet:
    def test_set_and_get_single(self, db):
        db.set_persona("name", "Alice")
        assert db.get_persona("name") == "Alice"

    def test_get_nonexistent_key(self, db):
        assert db.get_persona("nonexistent") is None

    def test_get_all_empty(self, db):
        assert db.get_persona() == {}

    def test_set_multiple_and_get_all(self, db):
        db.set_persona("name", "Bob")
        db.set_persona("role", "Engineer")
        db.set_persona("communication_style", "concise")
        result = db.get_persona()
        assert result == {"name": "Bob", "role": "Engineer", "communication_style": "concise"}

    def test_overwrite_value(self, db):
        db.set_persona("name", "Alice")
        db.set_persona("name", "Bob")
        assert db.get_persona("name") == "Bob"


class TestPersonaUpdate:
    def test_batch_update(self, db):
        db.update_persona({"name": "Carol", "role": "Designer"})
        assert db.get_persona("name") == "Carol"
        assert db.get_persona("role") == "Designer"


class TestPersonaClear:
    def test_clear_all(self, db):
        db.set_persona("name", "Dave")
        db.set_persona("role", "Dev")
        db.clear_persona()
        assert db.get_persona() == {}


class TestPersonaPrompt:
    def test_empty_prompt(self, db):
        assert db.get_persona_prompt() == ""

    def test_formatted_prompt(self, db):
        db.set_persona("name", "Eve")
        db.set_persona("role", "PM")
        prompt = db.get_persona_prompt()
        assert "## User Profile" in prompt
        assert "Eve" in prompt
        assert "PM" in prompt


class TestPersonaPersistence:
    def test_survives_reopen(self, tmp_path):
        db1 = LociDB(path=tmp_path / "persist.loci")
        db1.set_persona("name", "Frank")
        db1.close()

        db2 = LociDB(path=tmp_path / "persist.loci")
        assert db2.get_persona("name") == "Frank"
        db2.close()
