package core

import (
	"fmt"
	"os"
	"time"

	"gopkg.in/yaml.v2"

	clabtypes "github.com/srl-labs/containerlab/types"
)

type LabState struct {
	Topology *clabtypes.Topology `yaml:"topology"`
}

// WriteState saves the topology to the state file.
func (c *CLab) WriteState() error {
	state := &LabState{
		Topology: c.Config.Topology,
	}

	data, err := yaml.Marshal(state)
	if err != nil {
		return fmt.Errorf("failed to marshal state: %w", err)
	}

	header := fmt.Sprintf("# generated by containerlab at %s\n", time.Now().Format(time.RFC3339))
	content := append([]byte(header), data...)

	statePath := c.TopoPaths.StateFile()
	if err := os.WriteFile(statePath, content, 0644); err != nil {
		return fmt.Errorf("failed to write state file %s: %w", statePath, err)
	}

	return nil
}

// LoadState reads the NodeConfigs from labdir/.state.clab.yaml.
func (c *CLab) LoadState() (*LabState, error) {
	statePath := c.TopoPaths.StateFile()

	data, err := os.ReadFile(statePath)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, nil
		}
		return nil, fmt.Errorf("failed to read state file %s: %w", statePath, err)
	}

	state := &LabState{}
	if err := yaml.Unmarshal(data, state); err != nil {
		return nil, fmt.Errorf("failed to unmarshal state: %w", err)
	}

	return state, nil
}
