package tilt

import (
	"encoding/json"
	"fmt"
	"os"
)

// ContextReport is the reviewable session handoff contract written by
// session_context_write. It carries generic session and substrate facts only:
// the Session Tiltfile owns the service graph (ADR 20260616).
type ContextReport struct {
	RuntimeID      string `json:"runtime_id,omitempty"`
	SessionName    string `json:"session_name"`
	Owner          string `json:"owner"`
	Namespace      string `json:"namespace"`
	Mode           string `json:"mode"`
	KubeContext    string `json:"kube_context"`
	KubeconfigPath string `json:"kubeconfig_path"`
	ContextPath    string `json:"context_path"`
	TiltfilePath   string `json:"tiltfile_path"`
}

// ContextIndex is the cp9-owned per-session context contract written by
// session_context_write.
type ContextIndex struct {
	RuntimeID         string             `json:"runtime_id,omitempty"`
	SessionName       string             `json:"session_name"`
	Owner             string             `json:"owner"`
	Namespace         string             `json:"namespace"`
	GitHubAppClientID string             `json:"github_app_client_id"`
	EssentialV2       ContextEssentialV2 `json:"essential_v2"`
}

type ContextEssentialV2 struct {
	Enabled                  bool     `json:"enabled"`
	EnabledTiKVRemoteWorkers []string `json:"enabled_tikv_remote_workers"`
}

// LoadContextReport reads the generated Tilt context report from disk.
func LoadContextReport(path string) (*ContextReport, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("read context report: %w", err)
	}
	var report ContextReport
	if err := json.Unmarshal(data, &report); err != nil {
		return nil, fmt.Errorf("parse context report: %w", err)
	}
	return &report, nil
}

// LoadContextIndex reads the generated cp9 context index from disk.
func LoadContextIndex(path string) (*ContextIndex, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("read context index: %w", err)
	}
	var index ContextIndex
	if err := json.Unmarshal(data, &index); err != nil {
		return nil, fmt.Errorf("parse context index: %w", err)
	}
	return &index, nil
}
