package devcontainer

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

/*
   Dev container provisioning helpers.

   This file is intentionally small and boring.
   It exists to support idempotency and shared paths
   across dev container runtimes.
*/

const (
	// MarkerDir is where devcontainer state is stored.
	MarkerDir = "/opt/zlh/.zlh"

	// ReadyMarker is written after a dev container is fully provisioned.
	ReadyMarker = "devcontainer_ready.json"
)

// ReadyMarkerPath returns the absolute path to the ready marker file.
func ReadyMarkerPath() string {
	return filepath.Join(MarkerDir, ReadyMarker)
}

// IsProvisioned returns true if the dev container has already been installed.
func IsProvisioned() bool {
	_, err := os.Stat(ReadyMarkerPath())
	return err == nil
}

// WriteReadyMarker records successful dev container provisioning.
// This should be called by runtime installers AFTER all install steps succeed.
func WriteReadyMarker(runtime string) error {

	if err := os.MkdirAll(MarkerDir, 0755); err != nil {
		return err
	}

	data := map[string]any{
		"runtime": runtime,
		"ready_at": time.Now().UTC().Format(time.RFC3339),
	}

	raw, err := json.MarshalIndent(data, "", "  ")
	if err != nil {
		return err
	}

	return os.WriteFile(ReadyMarkerPath(), raw, 0644)
}
