package promptcompiler

import "encoding/json"

// RenderedText exposes immutable compiler-rendered block text to attribution
// consumers. There is no exported field or setter that lets callers author it.
func (b PromptBlock) RenderedText() string { return b.text }

func (b *PromptBlock) UnmarshalJSON(data []byte) error {
	var wire struct {
		ID            string          `json:"id"`
		Title         string          `json:"title"`
		Type          BlockType       `json:"type"`
		Layer         BlockLayer      `json:"layer"`
		Slot          OutputSlot      `json:"slot"`
		Durability    Durability      `json:"durability"`
		Priority      int             `json:"priority"`
		Source        PromptSourceRef `json:"source"`
		Text          string          `json:"text"`
		TokenEstimate int             `json:"tokenEstimate"`
		Tags          []string        `json:"tags,omitempty"`
		DebugLabel    string          `json:"debugLabel"`
	}
	if err := json.Unmarshal(data, &wire); err != nil {
		return err
	}
	*b = PromptBlock{ID: wire.ID, Title: wire.Title, Type: wire.Type, Layer: wire.Layer, Slot: wire.Slot, Durability: wire.Durability, Priority: wire.Priority, Source: wire.Source, text: wire.Text, TokenEstimate: wire.TokenEstimate, Tags: wire.Tags, DebugLabel: wire.DebugLabel}
	return nil
}

func (b PromptBlock) MarshalJSON() ([]byte, error) {
	type wire struct {
		ID            string          `json:"id"`
		Title         string          `json:"title"`
		Type          BlockType       `json:"type"`
		Layer         BlockLayer      `json:"layer"`
		Slot          OutputSlot      `json:"slot"`
		Durability    Durability      `json:"durability"`
		Priority      int             `json:"priority"`
		Source        PromptSourceRef `json:"source"`
		Text          string          `json:"text"`
		TokenEstimate int             `json:"tokenEstimate"`
		Tags          []string        `json:"tags,omitempty"`
		DebugLabel    string          `json:"debugLabel"`
	}
	return json.Marshal(wire{b.ID, b.Title, b.Type, b.Layer, b.Slot, b.Durability, b.Priority, b.Source, b.text, b.TokenEstimate, b.Tags, b.DebugLabel})
}
