---
name: api-simplex
description: >
  Expert guide for using the SimplexPro REST API. Use this when you need to implement integrations, 
  manage requests (GET, POST, PUT, DELETE), understand JSON schemas for Linear Programming models 
  (Simplex/Graphic), or use Python client functions to interact with the server.
---

# SimplexPro API Documentation

This skill empowers the assistant to handle all SimplexPro REST API operations, ensuring data is sent and received correctly according to defined schemas.

## API Base Path: `/problemas`

## Endpoint Summary

### 1. List Problems
Retrieves a paginated list of registered problems.

- **Route**: `GET /problemas`
- **Query Params**: `page` (int, default=1).
- **Response JSON (`List[ResumenProblema]`)**:
  ```json
  [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "titulo": "Wood Factory",
      "descripcion": "Monthly production optimization",
      "tipoOptimizacion": "MAX",
      "metodo": "Grafico",
      "fechaCreacion": "2026-05-14"
    }
  ]
  ```

### 2. Get Problem Solution
Retrieves the solution details for a registered problem. The response model dynamically matches either `MostrarResultadoGrafico` or `MostrarResultadoSimplex` based on the method used.

- **Route**: `GET /problemas/{id}`
- **Response JSON (Graphic Method - `MostrarResultadoGrafico`)**:
  ```json
  {
    "id": "uuid-string",
    "titulo": "Wood Factory",
    "descripcion": "Monthly production optimization",
    "tipoOptimizacion": "MAX",
    "metodo": "Grafico",
    "fechaCreacion": "2026-05-14",
    "funcion_objetivo": "MAX Z = 5x + 4y",
    "mensaje": "The optimal solution is 2 Table and 4 Chair, with Z = 26.00",
    "valoresFO": ["Z(2.00, 4.00) = 5*(2) + 4*(4) = 26.00 (MAX)"],
    "grafico": "iVBORw0KGgoAAAANSUhEUgA...",
    "variables": { "x": "Table", "y": "Chair" },
    "restricciones": [
      { "inecuacion": "2x + 1y <= 10", "glosa": "Wood limit" }
    ]
  }
  ```
- **Response JSON (Simplex Method - `MostrarResultadoSimplex`)**:
  ```json
  {
    "id": "uuid-string",
    "titulo": "Factory Optimization",
    "descripcion": "Maximize profit",
    "tipoOptimizacion": "MAX",
    "metodo": "Simplex",
    "fechaCreacion": "2026-05-14",
    "valorFO": "MAX Z = 10x1 + 15x2 = 150",
    "mensaje": "The optimal solution is 10 Chair with Z = 150",
    "funcion_objetivo": "MAX Z = 10x1 + 15x2",
    "iteraciones": [
      {
        "iteracion": 1,
        "entra": "x2",
        "sale": "S1",
        "razonMinima": 10.0,
        "elementoPivote": 1.0,
        "tabla": {
          "header": ["Base", "x1", "x2", "S1", "Sol"],
          "row1": ["S1", "2", "1", "1", "10"],
          "Z": ["Z", "-10", "-15", "0", "0"]
        }
      }
    ],
    "variables": { "x1": "Table", "x2": "Chair" },
    "restricciones": [
      { "inecuacion": "2x1 + 1x2 <= 10", "glosa": "Resource A" }
    ]
  }
  ```

### 4. Register Problem
Creates a new problem and calculates its solution.

- **Route**: `POST /problemas/registrar?metodo=grafico|simplex`
- **Request Body (Graphic Example)**:
  ```json
  {
    "titulo": "New Graphic Problem",
    "descripcion": "Optional description",
    "variables": { "x": "Product A", "y": "Product B" },
    "restricciones": [
      { "x": 2, "y": 3, "signo": "<=", "constante": 12, "glosa": "Constraint 1" }
    ],
    "funcion_objetivo": { "x": 10, "y": 15, "tipo": "max" }
  }
  ```
- **Request Body (Simplex Example)**:
  ```json
  {
    "titulo": "New Simplex Problem",
    "descripcion": "Optimization of production resources",
    "variables": { "x1": "Var 1", "x2": "Var 2", "x3": "Var 3" },
    "restricciones": [
      {
        "terminos": {
          "x1": 1,
          "x2": 1,
          "x3": 1
        },
        "signo": "=",
        "constante": 50
      }
    ],
    "funcion_objetivo": {
      "terminos": {
          "x1": 1,
          "x2": 1,
          "x3": 1
        },
      "tipo": "min"
    }
  }
  ```
- **Response JSON**: `{"id": "new-uuid-string"}`

### 5. Update Problem
Updates an existing problem by its ID.

- **Route**: `PUT /problemas/actualizar?metodo=grafico|simplex&id={id}`
- **Request Body**: Same structure as Register.
- **Response JSON**: `{"mensaje": "Problema actualizado"}`

### 6. Delete Problem
- **Route**: `DELETE /problemas/eliminar/{id}`
- **Response JSON**: `{"mensaje": "Problema eliminado"}`

## Validation and Error Messages

The API performs strict validation on input data. Below are the common error messages returned in the `detail` field of a **400 Bad Request** response.

### General & Root Level
- `"{field} es requerido"`: One of the required root fields (`titulo`, `variables`, `restricciones`, `funcion_objetivo`) is missing.
- `"Metodo no valido"`: The `metodo` query parameter is not `grafico` or `simplex`.
- `"Pagina no valida"`: The `page` query parameter is less than 1.

### Graphic Method Specific (`validar_problema_grafico`)
- **Variables**:
  - `"variables es requerido"`: The `variables` field is not a valid dictionary.
  - `"La variable '{var}' es requerida"`: Key `'x'` or `'y'` is missing in the `variables` dictionary.
  - `"El nombre de la variable '{var}' es requerido"`: The value for `'x'` or `'y'` is empty or not a string.
- **Constraints (`restricciones`)**:
  - `"restricciones es requerido"`: The list is empty or not a valid list.
  - `"la restricción ({idx}): no es valido"`: The constraint at index `idx` is not a dictionary.
  - `"la restricción ({idx}): falta coeficiente '{var}'"`: Missing key `'x'` or `'y'` in constraint.
  - `"la restricción ({idx}): coeficiente '{var}' no es valido"`: Coefficient is not a number.
  - `"la restricción ({idx}): falta signo"`: Key `signo` is missing.
  - `"El signo de la restricción ({idx}) no es valido"`: Sign is not `=`, `<=`, or `>=`.
  - `"la restricción ({idx}): falta 'constante'"`: Key `constante` is missing.
  - `"la restricción ({idx}): constante no es valida"`: Constant value is not a number.
- **Objective Function (`funcion_objetivo`)**:
  - `"función objetivo requerido"`: Field is not a dictionary.
  - `"Coeficiente '{var}' en función objetivo requerido"`: Missing key `'x'` or `'y'`.
  - `"Coeficiente '{var}' en función objetivo debe ser numérico"`: Value is not a number.
  - `"Tipo de optimización requerido"`: Key `tipo` is missing.
  - `"Tipo de optimización inválido: '{val}'"`: Must be `max` or `min`.

### Simplex Method Specific (`validar_problema_simplex`)
- **Variables**:
  - `"Las variables no son validas."`: Empty or invalid variables dictionary.
  - `"Variable '{var}' no es valida."`: Key does not follow the `x1, x2, ...` pattern.
  - `"Nombre variable '{var}' inválido."`: Variable name is empty or not a string.
- **Constraints (`restricciones`)**:
  - `"Las restricciones no son validas."`: List is empty or invalid.
  - `"Restricción ({idx}): no es valida."`: Element in the list is not a dictionary.
  - `"Restricción ({idx}): los términos no son validos."`: The `terminos` field is not a dictionary.
  - `"Restricción ({idx}): la variable '{var}' no es valida."`: Variable in `terminos` does not match pattern `x1, x2...`.
  - `"Restricción ({idx}): {var}{coef} no es valido."`: Coefficient value is not numeric.
  - `"Restricción ({idx}): falta signo."`: Key `signo` is missing.
  - `"Restricción ({idx}): signo inválido."`: Sign is not in allowed set (`<=`, `>=`, `=`).
  - `"Restricción ({idx}): falta constante."`: Key `constante` is missing.
  - `"Restricción ({idx}): la constante debe ser numérica."`: Value is not a number.
- **Objective Function (`funcion_objetivo`)**:
  - `"'función objetivo' no es valida"`: Field is not a dictionary.
  - `"La función objetivo: la variable no es valida."`: Key in `terminos` is not a string or doesn't match `x1, x2...`.
  - `"La función objetivo: el coeficiente no es valido."`: Coefficient value in `terminos` is not numeric.
  - `"Tipo de optimización faltante en FO."`: Key `tipo` is missing.
  - `"Tipo '{val}' inválido. Use 'max' o 'min'."`: Optimization type not allowed.

### Other HTTP Errors
- **404 Not Found**: `"Problema no encontrado"` (When ID doesn't exist).
- **422 Unprocessable Entity**: Automatic Pydantic validation for schema types.

## Implementation Guidelines
1. **Method Check**: Always verify the `metodo` query parameter matches the data structure (Graphic requires 2 variables exactly).
2. **Variable Mapping**: Ensure constraints use the same keys defined in the `variables` dictionary.
3. **Graphic Constraints**: For the Graphic method, use keys `x` and `y` for coefficients.
4. **Simplex Constraints**: For the Simplex method, use keys `x1`, `x2`, ..., `xn`.