package com.openosrs.client.scripting;

import java.util.ArrayList;
import java.util.List;

/**
 * Script execution history tracking.
 */
public class ScriptExecutionHistory {
    private final String executionId;
    private final String scriptName;
    private final ScriptConfiguration configuration;
    private final long createdTime;
    private final List<ExecutionRecord> executions;
    
    public ScriptExecutionHistory(String executionId, String scriptName, ScriptConfiguration configuration) {
        this.executionId = executionId;
        this.scriptName = scriptName;
        this.configuration = configuration;
        this.createdTime = System.currentTimeMillis();
        this.executions = new ArrayList<>();
    }
    
    public void recordExecution() {
        executions.add(new ExecutionRecord(System.currentTimeMillis()));
    }
    
    public void recordCompletion(ScriptStatus status) {
        if (!executions.isEmpty()) {
            ExecutionRecord lastExecution = executions.get(executions.size() - 1);
            lastExecution.setCompletion(System.currentTimeMillis(), status);
        }
    }
    
    public String getExecutionId() { return executionId; }
    public String getScriptName() { return scriptName; }
    public ScriptConfiguration getConfiguration() { return configuration; }
    public long getCreatedTime() { return createdTime; }
    public List<ExecutionRecord> getExecutions() { return new ArrayList<>(executions); }
    
    public int getExecutionCount() { return executions.size(); }
    public long getTotalRuntime() {
        return executions.stream()
            .mapToLong(ExecutionRecord::getRuntime)
            .sum();
    }
    
    public static class ExecutionRecord {
        private final long startTime;
        private long endTime;
        private ScriptStatus status;
        
        public ExecutionRecord(long startTime) {
            this.startTime = startTime;
            this.status = ScriptStatus.RUNNING;
        }
        
        public void setCompletion(long endTime, ScriptStatus status) {
            this.endTime = endTime;
            this.status = status;
        }
        
        public long getStartTime() { return startTime; }
        public long getEndTime() { return endTime; }
        public ScriptStatus getStatus() { return status; }
        public long getRuntime() { return endTime > 0 ? endTime - startTime : System.currentTimeMillis() - startTime; }
    }
}