#!/usr/bin/env bash
#****************************************************************#
# ScriptName: cli.sh
# Author: @alibaba-inc.com
# Create Date: 2026-03-04 17:22
# Modify Author: @alibaba-inc.com
# Modify Date: 2026-03-25 14:27
# Function:
#***************************************************************#

#Environment Variables Configuration:
#--------------------------------------------------------------
#1. DASHSCOPE_API_KEY (Required)
#   - Sets the authentication key for DashScope API access
#   - Format: API key string (e.g., "ds-1234567890abcdef")
#
#2. LOG_LEVEL (Optional, default: 'info')
#   - Controls logging verbosity
#   - Allowed values: 'debug', 'info', 'warning', 'error', 'critical'
#
#3. FC_PYPI_LIB (Optional)
#   - Specifies local/alternative dashscope package installations
#   - Accepts space-separated list of wheel paths
#   - Default: Uses official PyPI 'dashscope' package
#   - Example: "./dist/dashscope-1.3.0-py3-none-any.whl ./custom_deps/custom_lib.whl"
#
#CLI Command Documentation:
#--------------------------------------------------------------
#1. Register Function Components
#   - Command: `dashscope rl register_functions`
#   - Function: Registers RL workflow components
#   - Key Options:
#     * --rollout-classpaths: Classpaths for rollout processors
#     * --reward-classpaths: Classpaths for reward calculators
#     * --group-reward-classpaths: Classpaths for group reward processors
#     * --no-lazy-load: Immediate component initialization
#   - Outputs: JSON with entity/instance IDs for registered components
#   - Example:
#     ```bash
#     dashscope rl register_functions \
#       --rollout-classpaths "rollout.Processor" \
#       --reward-classpaths "reward.Calculator" \
#       -o json
#     ```
#
#2. Test Component Functions
#   - Command: `dashscope rl test_functions <INSTANCE_ID>`
#   - Function: Validates component functionality
#   - Key Options:
#     * --type: Component type (rollout/reward/group_reward)
#     * --input: Test input JSON file path
#   - Test Types:
#     a. Rollout Test:
#        ```bash
#        dashscope rl test_functions "ro-ins-123" \
#          --type rollout \
#          --input rollout_test.json
#        ```
#     b. Reward Test:
#        ```bash
#        dashscope rl test_functions "rw-ins-456" \
#          --type reward \
#          --input reward_test.json
#        ```
#     c. Group Reward Test:
#        ```bash
#        dashscope rl test_functions "grw-ins-789" \
#          --type group_reward \
#          --input group_reward_test.json
#        ```
#
#3. Data Management
#   - Command: `dashscope rl upload_data`
#   - Function: Uploads training datasets
#   - Key Options:
#     * --training-files: Paths to training datasets
#     * --validation-files: Paths to validation datasets
#   - Output: Uploaded dataset IDs
#   - Example:
#     ```bash
#     dashscope rl upload_data \
#       --training-files "./data/train.jsonl" \
#       -o json
#     ```
#
#4. Run Complete Workflow
#   - Command: `dashscope rl run`
#   - Function: End-to-end RL job submission and execution
#   - Operation Modes:
#     a. Config-Driven Mode:
#        ```bash
#        dashscope rl run -c job.yaml -o json
#        ```
#   - Key Options:
#     * -c/--config: YAML configuration file path
#     * --verbose: Show detailed execution logs
#
#5. Job Lifecycle Management
#   - Status Check:
#     ```bash
#     dashscope rl get <JOB_ID> -o json
#     ```
#   - Log Retrieval:
#     ```bash
#     dashscope rl logs <JOB_ID> --lines 50
#     ```
#   - Job Listing:
#     ```bash
#     dashscope rl list --page 1 --size 10
#     ```
#   - Job Termination:
#     ```bash
#     dashscope rl cancel <JOB_ID>
#     ```
#   - Job Deletion:
#     ```bash
#     dashscope rl delete <JOB_ID>
#     ```
#
#Output Formats:
#------------------------------------------------------------------------
#| Option       | Description                  | Use Case               |
#|--------------|------------------------------|------------------------|
#| -o json      | Machine-readable JSON        | Automation pipelines   |
#| (default)    | Human-friendly table format  | Interactive debugging  |
#
#All commands support --help for detailed parameter information.

# Register functions
# output：
#{
#  "rollout_entity_ids": [
#    "ro-750a55c1-6855-4e07-ad57-fb4caa1607bc"
#  ],
#  "reward_entity_ids": [
#    "rw-cfaf35ee-eae8-4fdf-bf39-b7638955ed07",
#    "rw-ba974a37-a5e9-4941-9aac-784da9c48ef1"
#  ],
#  "rollout_instance_ids": [
#    "ro-ins-3ca12060-384d-48a5-85a5-469580996d9e"
#  ],
#  "reward_instance_ids": [
#    "rw-ins-a5940167-1ed3-48ff-bb45-43b847c81044",
#    "rw-ins-3daeb221-365f-433e-9e62-520d28ed2990"
#  ]
#}
dashscope rl register_functions \
  --rollout-classpaths "functions.rollout.rollout2.DemoRolloutProcessor" \
  --reward-classpaths "functions.reward.reward.DemoRewardProcessor" \
  --reward-classpaths "functions/reward/reward_decorator.py:SafetyProcessor" \
  --group-reward-classpaths "functions.reward.group_reward.DemoGroupRewardProcessor" \
  --no-lazy-load \
  --output-format json

# Test Rollout function
# output：
#{
#  "agent_output": {
#    "messages": [
#      {
#        "role": "user",
#        "content": "Hello, please introduce yourself"
#      }
#    ],
#    "rollout_extra": {
#      "rollout_id": "ro-ins-e8e92e94-b5c3-4546-b7b1-9832b8b948f2",
#      "training_state": {
#        "task_id": "task-001"
#      }
#    },
#    "rollout_metrics": {
#      "latency": 0.0001
#    },
#    "reward_score": null
#  },
#  "status": "success",
#  "error": null
##}
ROLLOUT_INSTANCE_ID="ro-ins-72d14e90-a4c8-4a3d-aa0d-1fa0109d824d"
dashscope rl test_functions "$ROLLOUT_INSTANCE_ID" \
  --type rollout \
  --input ./resources/rollout_input.json

# Test Reward function
# output：
#{
#  "reward": {
#    "reward_score": 0.0,
#    "rollout_metrics": {
#      "accuracy": 0.95
#    }
#  },
#  "status": "success",
#  "error": null
#}
REWARD_INSTANCE_ID="rw-ins-03a1cfe5-087e-4010-a286-c91933c6bb64"
dashscope rl test_functions "$REWARD_INSTANCE_ID" \
  --type reward \
  --input ./resources/reward_input.json

# Test Reward function
# output：
#{
#  "reward": {
#    "reward_score": 0.85,
#    "reward_metrics": null
#  },
#  "status": "success",
#  "error": null
#}
REWARD_INSTANCE_ID="rw-ins-c85ec84e-d82a-4d26-96cc-e5e297106937"
dashscope rl test_functions "$REWARD_INSTANCE_ID" \
  --type reward \
  --input ./resources/reward_decorator_input.json

# Test Group Reward function
# output：
#{
#  "group_reward": {
#    "reward_score": 0.0,
#    "reward_metrics": {
#      "accuracy": 0.95
#    }
#  },
#  "status": "success",
#  "error": null
#}
GROUP_REWARD_INSTANCE_ID="grw-ins-05996ec9-6052-4d39-9c7c-ba3f5a0a77bf"
dashscope rl test_functions "$GROUP_REWARD_INSTANCE_ID" \
  --type group_reward \
  --input ./resources/group_reward_input.json

# Upload dataset
# output:
#{
#  "uploaded_training_ids": [
#    "531ab326-07d1-4cef-bc7f-afd34b941208"
#  ],
#  "uploaded_validation_ids": []
#}
dashscope rl upload_data --training-files "./data/training.jsonl" -o json
TRAIN_ID="13822545-4da6-4e62-809a-1e7b26d1b491"

# Submit and wait in non-interactive mode
# output:
#{
#  "job_id": "ft-202604061138-b031-poc",
#  "status": "PENDING",
#  "message": ""
#}
dashscope rl run -c job.yaml -o json
JOB_ID="ft-202604291430-02f2-poc"

# Check status
# output:
#{
#  "job_id": "ft-202604291430-02f2-poc",
#  "status": "RUNNING",
#  "created_at": "1654290265984853"
#}
dashscope rl get "$JOB_ID" -o json


# Fetch paginated logs
# output:
#┏━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━┓
#┃ Key    ┃ Value                    ┃
#┡━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━┩
#│ job_id │ ft-202604291430-02f2-poc │
#│ logs   │ []                       │
#└────────┴──────────────────────────┘
dashscope rl logs "$JOB_ID" --offset 1 --lines 50

# Result
#┏━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
#┃ Key       ┃ Value                                                                      ┃
#┡━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
#│ jobs      │ [                                                                          │
#│           │   {                                                                        │
#│           │     "job_id": "ft-202604221545-f777-poc",                                  │
#│           │     "job_name": "agentic-rl-1b9b480c",                                     │
#│           │     "status": "RUNNING",                                                   │
#│           │     "finetuned_output": "qwen3-4b-instruct-2507-ft-202604221545-f777-poc", │
#│           │     "model": "qwen3-4b-instruct-2507",                                     │
#│           │     "base_model": "qwen3-4b-instruct-2507",                                │
#│           │     "training_file_ids": [                                                 │
#│           │       "77eb325b-fc38-42d5-a0f9-65b72f3fad13"                               │
#│           │     ],                                                                     │
#│           │     "validation_file_ids": [                                               │
#│           │       "4963037d-9c18-4b1d-ac12-5afc7d0586f2"                               │
#│           │     ],                                                                     │
#│           │     "training_datasets": [],                                               │
#│           │     "validation_datasets": [],                                             │
#│           │     "hyper_parameters": {                                                  │
#│           │       "n_epochs": 5,                                                       │
#│           │       "learning_rate": 1e-06,                                              │
#│           │       "max_prompt_length": 1024,                                           │
#│           │       "batch_size": 128                                                    │
#│           │     },                                                                     │
#│           │     "training_type": "reinforcement",                                      │
#│           │     "create_time": "2026-04-22 15:45:46",                                  │
#│           │     "workspace_id": "llm-5rwyknsoxp4y7h5u",                                │
#│           │     "user_identity": "1654290265984853",                                   │
#│           │     "modifier": "1654290265984853",                                        │
#│           │     "creator": "1654290265984853",                                         │
#│           │     "group": "llm",                                                        │
#│           │     "model_name": "agentic-rl-1b9b480c",                                   │
#│           │     "max_output_cnt": 2                                                    │
#│           │   }                                                                        │
#│           │ ]                                                                          │
#│ page_no   │ 1                                                                          │
#│ page_size │ 10                                                                         │
#│ total     │ 5165                                                                       │
#└───────────┴────────────────────────────────────────────────────────────────────────────┘
dashscope rl list --page 1 --size 10

# output
# ✅ Job ft-202604291430-02f2-poc canceled successfully
#dashscope rl cancel "$JOB_ID"

#dashscope rl delete "$JOB_ID"
