# state.py — Python direct state loader for agent-sessions.yaml / agent-sessions.db (N7)

import os, json, sqlite3
from typing import Dict, Any

def load_state_json(yaml_path: str = None) -> Dict[str, Any]:
    if not yaml_path:
        yaml_path = os.environ.get('AGENT_SESSIONS_YAML') or os.environ.get('YAML_PATH', '')
    if not yaml_path:
        return {}

    db_path = os.path.splitext(yaml_path)[0] + '.db'
    d = {}
    db_sessions = []
    try:
        if os.path.exists(db_path):
            conn = sqlite3.connect(db_path, timeout=60.0)
            conn.execute('PRAGMA busy_timeout = 60000')
            try:
                row = conn.execute('SELECT data FROM state WHERE id=1').fetchone()
                if row:
                    d = json.loads(row[0])
            except sqlite3.OperationalError:
                pass
            try:
                cursor = conn.execute('SELECT data FROM sessions')
                for r in cursor.fetchall():
                    db_sessions.append(json.loads(r[0]))
                d['herdr_sessions'] = db_sessions
            except sqlite3.OperationalError:
                pass
            conn.close()
        elif os.path.exists(yaml_path):
            import yaml
            with open(yaml_path) as f:
                d = yaml.safe_load(f) or {}
    except Exception:
        pass

    def clean_surrogates(obj):
        if isinstance(obj, str):
            return obj.encode('utf-8', errors='replace').decode('utf-8')
        elif isinstance(obj, dict):
            return {k: clean_surrogates(v) for k, v in obj.items()}
        elif isinstance(obj, list):
            return [clean_surrogates(x) for x in obj]
        return obj

    return clean_surrogates(d)
