import json

from .base import BaseRepo


class StateRepo(BaseRepo):

    def get(self) -> dict | None:
        row = self.conn.execute("SELECT * FROM session_state WHERE project_dir=?", (self.project_dir,)).fetchone()
        if not row:
            return None
        d = dict(row)
        for key in ("progress", "recent_changes", "pending"):
            if key in d and isinstance(d[key], str):
                d[key] = json.loads(d[key])
        return d

    def upsert(self, state: dict) -> dict:
        existing = self.get()
        for key in ("progress", "recent_changes", "pending"):
            if key in state and isinstance(state[key], list):
                state[key] = json.dumps(state[key], ensure_ascii=False)
        
        state["updated_at"] = self._now()
        
        if existing:
            fields = {k: v for k, v in state.items() if k != "id"}
            if fields:
                set_clause = ", ".join(f"{k}=?" for k in fields)
                self.conn.execute(f"UPDATE session_state SET {set_clause} WHERE project_dir=?",
                                  [*fields.values(), self.project_dir])
        else:
            state["project_dir"] = self.project_dir
            cols = ", ".join(state.keys())
            placeholders = ", ".join("?" * len(state))
            self.conn.execute(f"INSERT INTO session_state ({cols}) VALUES ({placeholders})",
                              list(state.values()))
        
        self._commit()
        return self.get()
