"""Simulation result model."""
import json
from datetime import datetime
from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey, Float

from ..database import Base


class SimulationResult(Base):
    """A single simulation result row (from scan_results.csv)."""
    __tablename__ = "simulation_results"

    id = Column(Integer, primary_key=True, index=True)
    plan_id = Column(Integer, ForeignKey("simulation_plans.id"), nullable=False, index=True)
    run_index = Column(Integer, default=0)
    status = Column(String(20), default="OK")  # OK / FAILED / UNCERTAIN
    solve_time_s = Column(Float, default=0.0)
    params_json = Column(Text, default="{}")  # JSON: parameter values
    metrics_json = Column(Text, default="{}")  # JSON: metric values
    error_message = Column(Text, default="")
    created_at = Column(DateTime, default=datetime.utcnow)

    def get_params(self) -> dict:
        try:
            return json.loads(self.params_json) if self.params_json else {}
        except (json.JSONDecodeError, TypeError):
            return {}

    def set_params(self, data: dict) -> None:
        self.params_json = json.dumps(data, ensure_ascii=False)

    def get_metrics(self) -> dict:
        try:
            return json.loads(self.metrics_json) if self.metrics_json else {}
        except (json.JSONDecodeError, TypeError):
            return {}

    def set_metrics(self, data: dict) -> None:
        self.metrics_json = json.dumps(data, ensure_ascii=False)
