#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Helper operations for pulse proposals command."""
from __future__ import annotations

import json
from pathlib import Path

def load_sessions(proposals_dir: Path) -> list[dict]:
    """Load all session files, sorted newest first."""
    if not proposals_dir.exists():
        return []
    sessions = []
    for f in sorted(proposals_dir.glob("session_*.json"), reverse=True):
        try:
            data = json.loads(f.read_text(encoding="utf-8"))
            data["_filepath"] = str(f)
            sessions.append(data)
        except (json.JSONDecodeError, OSError):
            continue
    return sessions


def save_session(session: dict, proposals_dir: Path):
    """Write a session back to disk."""
    filepath_str = session.get("_filepath", "")
    # Strip internal field before writing
    clean = {k: v for k, v in session.items() if k != "_filepath"}
    filepath = Path(filepath_str) if filepath_str else proposals_dir / f"{session['id']}.json"
    filepath.write_text(
        json.dumps(clean, indent=2, ensure_ascii=False), encoding="utf-8"
    )
    session["_filepath"] = str(filepath)


def _load_task_board(task_board_path: Path) -> dict:
    if not task_board_path.exists():
        return {"dispatches": []}
    try:
        return json.loads(task_board_path.read_text(encoding="utf-8"))
    except (json.JSONDecodeError, OSError):
        return {"dispatches": []}

def _save_task_board(board: dict, task_board_path: Path):
    task_board_path.write_text(json.dumps(board, indent=2, ensure_ascii=False), encoding="utf-8")


def load_legacy(legacy_file: Path) -> list[dict]:
    """Load legacy single-file proposals (governance votes)."""
    if not legacy_file.exists():
        return []
    try:
        data = json.loads(legacy_file.read_text(encoding="utf-8"))
        if isinstance(data, list):
            return data
        if isinstance(data, dict):
            if any(isinstance(v, dict) for v in data.values()):
                return list(data.values())
            return [data]
        return []
    except (json.JSONDecodeError, OSError):
        return []


def parse_ref(ref: str) -> tuple[int, int | None]:
    """Parse 'S' or 'S.I' reference into (session_idx, idea_idx)."""
    if "." in ref:
        parts = ref.split(".", 1)
        return int(parts[0]), int(parts[1])
    return int(ref), None
