package service

import (
	"encoding/json"
	"os"
	"path/filepath"
)

func (a *App) artifacts() map[string]ArtifactSummary {
	a.mu.RLock()
	defer a.mu.RUnlock()
	result := make(map[string]ArtifactSummary, len(a.artifactStore))
	for key, value := range a.artifactStore {
		result[key] = value
	}
	return result
}

func (a *App) loadArtifacts() error {
	data, err := os.ReadFile(a.settings.ArtifactStatePath)
	if err != nil {
		return err
	}
	var artifacts map[string]ArtifactSummary
	if err := json.Unmarshal(data, &artifacts); err != nil {
		return err
	}
	a.mu.Lock()
	a.artifactStore = artifacts
	a.mu.Unlock()
	return nil
}

func (a *App) persistArtifacts() error {
	a.mu.RLock()
	data, err := json.MarshalIndent(a.artifactStore, "", "  ")
	a.mu.RUnlock()
	if err != nil {
		return err
	}
	if err := os.MkdirAll(filepath.Dir(a.settings.ArtifactStatePath), 0o755); err != nil {
		return err
	}
	return os.WriteFile(a.settings.ArtifactStatePath, data, 0o644)
}

func (a *App) recordArtifact(summary ArtifactSummary) error {
	a.mu.Lock()
	a.artifactStore[summary.Node] = summary
	a.mu.Unlock()
	return a.persistArtifacts()
}
