import sqlite3

class NPCMemory:
    def __init__(self):
        self.conn = sqlite3.connect('npc_memory.db')
        self.create_tables()
    
    def create_tables(self):
        self.conn.execute('''
            CREATE TABLE IF NOT EXISTS npc_conversations (
                npc_id TEXT,
                player_id TEXT,
                message TEXT,
                response TEXT,
                timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
            )
        ''')
        self.conn.execute('''
            CREATE TABLE IF NOT EXISTS npc_relationships (
                npc_id TEXT,
                player_id TEXT,
                affinity INTEGER DEFAULT 0,
                last_interaction DATETIME
            )
        ''')
        self.conn.commit()

    def log_conversation(self, npc_id, player_id, message, response):
        self.conn.execute(
            'INSERT INTO npc_conversations (npc_id, player_id, message, response) VALUES (?, ?, ?, ?)',
            (npc_id, player_id, message, response)
        )
        self.conn.commit()

    def update_affinity(self, npc_id, player_id, delta):
        cur = self.conn.cursor()
        cur.execute('SELECT affinity FROM npc_relationships WHERE npc_id=? AND player_id=?', (npc_id, player_id))
        row = cur.fetchone()
        if row:
            new_affinity = row[0] + delta
            cur.execute('UPDATE npc_relationships SET affinity=?, last_interaction=CURRENT_TIMESTAMP WHERE npc_id=? AND player_id=?',
                        (new_affinity, npc_id, player_id))
        else:
            cur.execute('INSERT INTO npc_relationships (npc_id, player_id, affinity, last_interaction) VALUES (?, ?, ?, CURRENT_TIMESTAMP)',
                        (npc_id, player_id, delta))
        self.conn.commit()

    def get_conversation(self, npc_id, player_id, limit=3):
        """Return the last `limit` (default 3) (player_msg, npc_reply) tuples for this NPC/player."""
        cursor = self.conn.execute(
            '''
            SELECT message, response FROM npc_conversations
            WHERE npc_id = ? AND player_id = ?
            ORDER BY timestamp DESC
            LIMIT ?
            ''',
            (npc_id, player_id, limit)
        )
        # Return in chronological order (oldest first)
        rows = cursor.fetchall()
        return rows[::-1]

    def get_affinity(self, npc_id, player_id):
        """Return the affinity value for this NPC/player, or 0 if not set."""
        cursor = self.conn.execute(
            '''
            SELECT affinity FROM npc_relationships
            WHERE npc_id = ? AND player_id = ?
            ''',
            (npc_id, player_id)
        )
        row = cursor.fetchone()
        return row[0] if row else 0