"""registry.version — Agent version management + rollback."""
from __future__ import annotations
import json, hashlib
from typing import List, Dict, Optional
from agentpaas.db.session import get_db
from agentpaas.db.models import now_utc


def list_versions(agent_id: str) -> List[Dict]:
    db = get_db()
    return db.fetchall("SELECT * FROM agent_versions WHERE agent_id=? ORDER BY version DESC", (agent_id,))

def create_version(agent_id: str, config: dict, changelog: str = "", created_by: str = "") -> int:
    db = get_db()
    config_json = json.dumps(config, ensure_ascii=False)
    config_hash = hashlib.sha256(config_json.encode()).hexdigest()
    last = db.fetchone("SELECT version, config_hash FROM agent_versions WHERE agent_id=? ORDER BY version DESC LIMIT 1", (agent_id,))
    if last and last["config_hash"] == config_hash:
        return last["version"]
    new_ver = (last["version"] + 1) if last else 1
    db.execute("INSERT INTO agent_versions (agent_id, version, config, config_hash, changelog, created_by, created_at) VALUES (?,?,?,?,?,?,?)",
               (agent_id, new_ver, config_json, config_hash, changelog, created_by, now_utc()))
    db.execute("UPDATE agents SET current_version=?, updated_at=? WHERE id=?", (new_ver, now_utc(), agent_id))
    db.commit()
    return new_ver

def rollback(agent_id: str, target_version: int) -> bool:
    db = get_db()
    v = db.fetchone("SELECT * FROM agent_versions WHERE agent_id=? AND version=?", (agent_id, target_version))
    if not v:
        return False
    db.execute("UPDATE agents SET current_version=?, updated_at=? WHERE id=?", (target_version, now_utc(), agent_id))
    db.commit()
    return True
