use std::collections::HashMap;
use std::ops::Deref;
use std::sync::{Arc, Mutex, PoisonError, Weak};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::versioning::{Repository, Route};
use crate::billing::PageQuery;
use crate::error::{Error, Result};
use crate::parrot::generative::{Content, Text};
use crate::shared::server::Room;
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct TermsSchedule {
pub total: f64,
pub upfront: f64,
pub duration: f64,
pub interval: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Terms {
Amount(f64),
Schedule(TermsSchedule),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum TicketStatus {
Active,
Rejected,
Fulfilled,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Ticket {
pub id: u64,
pub date: DateTime<Utc>,
pub issue: String,
pub status: TicketStatus,
}
#[derive(Clone)]
pub struct Constitution {
pub text: String,
pub articles: Vec<String>,
room: RuntimeRoom,
}
impl Constitution {
pub async fn amend(&mut self, article: &str) -> Result<()> {
self.articles.push(article.to_string());
self.room
.runtime
.articles
.lock()
.unwrap_or_else(PoisonError::into_inner)
.push(article.to_string());
self.room
.update(&json!({ "event": "amend-constitution", "article": article }));
Ok(())
}
}
struct Runtime {
name: String,
model: Text,
text: String,
articles: Mutex<Vec<String>>,
agents: Mutex<HashMap<String, Agent>>,
}
#[derive(Clone)]
pub struct RuntimeRoom {
room: Room,
runtime: Arc<Runtime>,
}
impl Deref for RuntimeRoom {
type Target = Room;
fn deref(&self) -> &Room {
&self.room
}
}
impl RuntimeRoom {
pub fn new(room: Room, state: &Value) -> RuntimeRoom {
RuntimeRoom {
room,
runtime: Arc::new(Runtime {
name: state["name"].as_str().unwrap_or_default().to_string(),
model: serde_json::from_value(state["model"].clone()).unwrap_or(Text::Auto),
text: state["constitution"]["text"]
.as_str()
.unwrap_or_default()
.to_string(),
articles: Mutex::new(
serde_json::from_value(state["constitution"]["articles"].clone())
.unwrap_or_default(),
),
agents: Mutex::new(HashMap::new()),
}),
}
}
pub fn name(&self) -> &str {
&self.runtime.name
}
pub fn constitution(&self) -> Constitution {
Constitution {
text: self.runtime.text.clone(),
articles: self
.runtime
.articles
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clone(),
room: self.clone(),
}
}
pub fn model(&self) -> Text {
self.runtime.model
}
pub fn agents(&self) -> HashMap<String, Agent> {
self.runtime
.agents
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clone()
}
pub fn update(&self, json: &Value) {
self.post(json);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum AgentStatus {
Active,
#[default]
Idle,
Deleted,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TimeRange {
pub start: DateTime<Utc>,
pub end: DateTime<Utc>,
pub max: Option<u32>,
}
#[derive(Debug, Clone)]
pub enum TimeRangeOrPage {
Range(TimeRange),
Page(PageQuery),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BalancePoint {
pub balance_micros: i64,
pub date: DateTime<Utc>,
}
struct AgentInner {
parent: Option<Weak<AgentInner>>,
id: String,
children: Mutex<Vec<Agent>>,
bible: String,
status: AgentStatus,
repository: Repository,
}
#[derive(Clone)]
pub struct Agent(Arc<AgentInner>);
fn not_implemented<T>() -> Result<T> {
Err(Error::Message(
"Termite routes are not implemented.".to_string(),
))
}
impl Agent {
pub fn new(
parent: Option<&Agent>,
id: &str,
bible: &str,
repository: Repository,
status: Option<AgentStatus>,
) -> Agent {
let agent = Agent(Arc::new(AgentInner {
parent: parent.map(|parent| Arc::downgrade(&parent.0)),
id: id.to_string(),
children: Mutex::new(Vec::new()),
bible: bible.to_string(),
status: status.unwrap_or_default(),
repository,
}));
if let Some(parent) = parent {
parent
.0
.children
.lock()
.unwrap_or_else(PoisonError::into_inner)
.push(agent.clone());
}
agent
}
pub fn parent(&self) -> Option<Agent> {
self.0.parent.as_ref().and_then(Weak::upgrade).map(Agent)
}
pub fn id(&self) -> &str {
&self.0.id
}
pub fn children(&self) -> Vec<Agent> {
self.0
.children
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clone()
}
pub fn bible(&self) -> &str {
&self.0.bible
}
pub fn status(&self) -> AgentStatus {
self.0.status
}
pub fn repository(&self) -> &Repository {
&self.0.repository
}
pub async fn ticket(&self, _issue: &str) -> Result<Ticket> {
not_implemented()
}
pub async fn delete(&self) -> Result<()> {
not_implemented()
}
pub async fn balance(&self, _query: TimeRangeOrPage) -> Result<Vec<BalancePoint>> {
not_implemented()
}
pub async fn contracts(&self, _query: TimeRangeOrPage) -> Result<Vec<Contract>> {
not_implemented()
}
pub async fn loans(&self, _query: TimeRangeOrPage) -> Result<Vec<Loan>> {
not_implemented()
}
pub async fn tickets(&self, _query: TimeRangeOrPage) -> Result<Vec<Ticket>> {
not_implemented()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum ContractStatus {
#[default]
Proposed,
Active,
Rejected,
Countered,
Defaulted,
Fulfilled,
}
#[derive(Clone)]
pub enum ContentOrContract {
Content(Content),
Contract(Box<Contract>),
}
#[derive(Debug, Clone)]
pub struct Validation {
pub repository: Repository,
pub route: Route,
}
#[derive(Clone)]
pub struct Contract {
pub parent: RuntimeRoom,
pub id: String,
pub principal: Agent,
pub contractor: Agent,
pub description: String,
pub settlement: Terms,
pub status: ContractStatus,
pub content: Vec<ContentOrContract>,
pub validation: Validation,
pub date: DateTime<Utc>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum LoanStatus {
#[default]
Proposed,
Active,
Rejected,
Defaulted,
Fulfilled,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct LoanTerms {
pub lender: Terms,
pub borrower: Terms,
}
#[derive(Clone)]
pub struct Loan {
pub parent: RuntimeRoom,
pub id: String,
pub lender: Agent,
pub borrower: Agent,
pub terms: LoanTerms,
pub status: LoanStatus,
pub date: DateTime<Utc>,
}