use std::collections::BTreeSet;
use std::env;
use std::error::Error;
use std::io;
use ziyuan_core::{Capability, Department, Office, Seal, TaskId, Template};
use super::Command;
#[derive(Debug)]
pub(crate) struct TemplateChoice {
pub(crate) name: String,
pub(crate) department: bool,
pub(crate) tools: bool,
pub(crate) mcp: bool,
pub(crate) scope: bool,
}
pub(crate) fn parse_edict(mut args: Vec<String>) -> Result<Command, Box<dyn Error>> {
const USAGE: &str = "用法: ziyuan edict [--plan] [--template <模板>] [--dept works] [--scope <路径>]... [--tools <工具,…>|none] [--mcp <授权,…>] [--queue] <诏令内容>
或: ziyuan edict --from-plan <诏令ID> [--scope <路径>]... [--no-tests] [--queue] [补充指示]
或: ziyuan edict --revise <诏令ID> [--scope <路径>]... [--no-tests] [--queue] [--note <修订指示>] [修订指示]\n 或: ziyuan edict --follow-up <诏令ID> [--dept <部门>] [--scope <路径>]... [--queue] <追问内容>\n 或: ziyuan edict --resume-failed <诏令ID> [--scope <路径>]... [--queue] [--note <补充指示>] [补充指示]";
let mut department = None;
let mut queue = false;
let mut plan_mode = false;
let mut from_plan: Option<TaskId> = None;
let mut revise: Option<TaskId> = None;
let mut follow_up: Option<TaskId> = None;
let mut resume_failed: Option<TaskId> = None;
let mut note_flag: Option<String> = None;
let mut no_tests = false;
let mut seal = Seal::default();
let mut scope = Vec::new();
let (mut template, mut tools_given, mut mcp_given) = (None, false, false);
while let Some(flag) = args.first().cloned() {
match flag.as_str() {
"--queue" => {
args.remove(0);
queue = true;
}
"--plan" => {
args.remove(0);
plan_mode = true;
}
"--no-tests" => {
args.remove(0);
no_tests = true;
}
"--from-plan" => {
if args.len() < 2 {
return Err(USAGE.into());
}
args.remove(0);
let value = args.remove(0);
from_plan = Some(TaskId(value.parse::<u64>().map_err(|_| USAGE)?));
}
"--revise" => {
if args.len() < 2 {
return Err(USAGE.into());
}
args.remove(0);
let value = args.remove(0);
revise = Some(TaskId(value.parse::<u64>().map_err(|_| USAGE)?));
}
"--follow-up" => {
if args.len() < 2 {
return Err(USAGE.into());
}
args.remove(0);
let value = args.remove(0);
follow_up = Some(TaskId(value.parse::<u64>().map_err(|_| USAGE)?));
}
"--resume-failed" => {
if args.len() < 2 {
return Err(USAGE.into());
}
args.remove(0);
let value = args.remove(0);
resume_failed = Some(TaskId(value.parse::<u64>().map_err(|_| USAGE)?));
}
"--note" => {
if args.len() < 2 {
return Err(USAGE.into());
}
args.remove(0);
note_flag = Some(args.remove(0));
}
"--dept" | "--scope" | "--tools" | "--template" | "--mcp" => {
if args.len() < 2 {
return Err(USAGE.into());
}
args.remove(0);
let value = args.remove(0);
match flag.as_str() {
"--dept" => department = Some(value.parse::<Department>()?),
"--scope" => scope.push(value),
"--template" => template = Some(value),
"--mcp" => {
seal.mcp = parse_mcp(&value);
mcp_given = true;
}
_ => {
seal.capabilities = parse_capabilities(&value)?;
tools_given = true;
}
}
}
_ => break,
}
}
let special_modes = usize::from(from_plan.is_some())
+ usize::from(revise.is_some())
+ usize::from(follow_up.is_some())
+ usize::from(resume_failed.is_some());
if special_modes > 1 {
return Err(
"`--from-plan`、`--revise`、`--follow-up` 与 `--resume-failed` 不能同时使用".into(),
);
}
if let Some(plan) = from_plan {
if plan_mode
|| template.is_some()
|| department.is_some()
|| tools_given
|| mcp_given
|| note_flag.is_some()
{
return Err(
"`--from-plan` 固定下发工部写诏令,不能同时使用 --plan / --template / --dept / --tools / --mcp / --note"
.into(),
);
}
return Ok(Command::EdictFromPlan {
plan,
scope,
run_tests: !no_tests,
queue,
extra: args.join(" "),
});
}
if let Some(source) = revise {
if plan_mode || template.is_some() || department.is_some() || tools_given || mcp_given {
return Err(
"`--revise` 固定下发工部修订诏令,不能同时使用 --plan / --template / --dept / --tools / --mcp"
.into(),
);
}
let trailing = args.join(" ");
let note = match (note_flag, trailing.is_empty()) {
(Some(n), true) => n,
(Some(n), false) if n.trim().is_empty() => trailing,
(Some(n), false) => format!("{n}\n{trailing}"),
(None, _) => trailing,
};
return Ok(Command::EdictRevise {
source,
scope,
run_tests: no_tests.then_some(false),
queue,
note,
});
}
if let Some(source) = follow_up {
if plan_mode
|| template.is_some()
|| tools_given
|| mcp_given
|| note_flag.is_some()
|| no_tests
{
return Err(
"`--follow-up` 固定以只读玉玺追查前件实录,不能同时使用 --plan / --template / --tools / --mcp / --note / --no-tests"
.into(),
);
}
let question = args.join(" ");
if question.trim().is_empty() {
return Err("`--follow-up` 须提供非空的追问内容".into());
}
return Ok(Command::EdictFollowUp {
source,
department,
scope,
queue,
question,
});
}
if let Some(source) = resume_failed {
if plan_mode
|| template.is_some()
|| department.is_some()
|| tools_given
|| mcp_given
|| no_tests
{
return Err(
"`--resume-failed` 沿用前次中断诏令的部门与玉玺授权,不能同时使用 --plan / --template / --dept / --tools / --mcp / --no-tests"
.into(),
);
}
let trailing = args.join(" ");
let note = match (note_flag, trailing.is_empty()) {
(Some(n), true) => n,
(Some(n), false) if n.trim().is_empty() => trailing,
(Some(n), false) => format!("{n}\n{trailing}"),
(None, _) => trailing,
};
return Ok(Command::EdictResumeFailed {
source,
scope,
queue,
note,
});
}
if note_flag.is_some() {
return Err("`--note` 只能配合 `--revise` 或 `--resume-failed` 使用".into());
}
if no_tests {
return Err("`--no-tests` 只能配合 `--from-plan` 或 `--revise` 使用".into());
}
if plan_mode {
if template.is_some() {
return Err("`--plan` 已按内置「条陈」模板下诏,不能同时指定 `--template`".into());
}
if tools_given && seal.capabilities.iter().any(|c| c.is_works_only()) {
return Err("条陈阶段只读,不得授予 write_file 或 run_tests".into());
}
template = Some(ziyuan_governance::PLAN_TEMPLATE.to_owned());
}
let template = template.map(|name| TemplateChoice {
name,
department: department.is_some(),
tools: tools_given,
mcp: mcp_given,
scope: !scope.is_empty(),
});
if args.is_empty() && template.is_none() {
return Err(USAGE.into());
}
if !scope.is_empty() {
let root = env::current_dir()?;
if let Some(missing) = scope.iter().find(|p| !root.join(p).exists()) {
return Err(format!("查阅范围不存在: {missing}").into());
}
seal.scope = scope;
}
let department = if let Some(department) = department {
department
} else {
let combined = args.join(" ").to_lowercase();
if combined.contains("任免") || combined.contains("官员") || combined.contains("考绩")
{
Department::Personnel
} else {
Department::Works
}
};
Ok(Command::Edict {
department,
text: args.join(" "),
queue,
seal,
template,
})
}
pub(crate) fn parse_template(mut args: Vec<String>) -> Result<Command, Box<dyn Error>> {
const USAGE: &str = "用法: ziyuan template | template save <名> [--dept works] [--scope <路径>]... [--tools <工具,…>|none] [--mcp <授权,…>] --criteria <甲;乙> <内容> | template rm <名>";
match args.first().map(String::as_str) {
None => return Ok(Command::Templates),
Some("rm") if args.len() == 2 => return Ok(Command::RemoveTemplate(args.remove(1))),
Some("save") if args.len() >= 2 => {}
_ => return Err(USAGE.into()),
}
args.remove(0);
let name = args.remove(0);
let mut template = Template {
department: Department::Works,
text: String::new(),
seal: Seal::default(),
criteria: Vec::new(),
};
let mut scope = Vec::new();
while let Some(flag) = args.first().cloned() {
if !matches!(
flag.as_str(),
"--dept" | "--scope" | "--tools" | "--mcp" | "--criteria"
) {
break;
}
if args.len() < 2 {
return Err(USAGE.into());
}
args.remove(0);
let value = args.remove(0);
match flag.as_str() {
"--dept" => template.department = value.parse()?,
"--scope" => scope.push(value),
"--tools" => template.seal.capabilities = parse_capabilities(&value)?,
"--mcp" => template.seal.mcp = parse_mcp(&value),
_ => {
template.criteria = value
.split([';', ';'])
.map(str::trim)
.filter(|c| !c.is_empty())
.map(str::to_owned)
.collect()
}
}
}
if !scope.is_empty() {
template.seal.scope = scope;
}
template.text = args.join(" ");
if template.text.trim().is_empty() || template.criteria.is_empty() {
return Err(USAGE.into());
}
Ok(Command::SaveTemplate { name, template })
}
pub(crate) fn parse_post(mut args: Vec<String>) -> Result<Command, Box<dyn Error>> {
const USAGE: &str =
"用法: ziyuan post [--dept works] [--station 驿站] [--urgent] <内容|-(从标准输入读取)>";
let (mut department, mut station, mut urgent) = (Department::Works, "驿站".to_owned(), false);
while let Some(flag) = args.first().cloned() {
match flag.as_str() {
"--urgent" => {
args.remove(0);
urgent = true;
}
"--dept" | "--station" if args.len() >= 2 => {
args.remove(0);
let value = args.remove(0);
if flag == "--dept" {
department = value.parse()?;
} else {
station = value;
}
}
"--dept" | "--station" => return Err(USAGE.into()),
_ => break,
}
}
let text = match args.as_slice() {
[] => return Err(USAGE.into()),
[dash] if dash == "-" => {
let mut text = String::new();
io::Read::read_to_string(&mut io::stdin(), &mut text)?;
text.trim().to_owned()
}
_ => args.join(" "),
};
Ok(Command::Post {
department,
station,
urgent,
text,
})
}
pub(crate) fn parse_ceiling(mut args: Vec<String>) -> Result<Command, Box<dyn Error>> {
const USAGE: &str = "用法: ziyuan ceiling <官职> [--scope <路径>]... [--tools <工具,…>|none] [--mcp <授权,…>|none] | default";
if args.is_empty() {
return Err(USAGE.into());
}
let office: Office = args.remove(0).parse()?;
if args == ["default"] {
return Ok(Command::Ceiling(office, None));
}
let mut seal = Seal {
mcp: ["*".to_owned()].into(),
..Seal::default()
};
let mut scope = Vec::new();
for pair in args.chunks(2) {
match pair {
[flag, value] if flag == "--scope" => scope.push(value.clone()),
[flag, value] if flag == "--tools" => seal.capabilities = parse_capabilities(value)?,
[flag, value] if flag == "--mcp" => seal.mcp = parse_mcp(value),
_ => return Err(USAGE.into()),
}
}
if args.is_empty() {
return Err(USAGE.into());
}
if !scope.is_empty() {
seal.scope = scope;
}
Ok(Command::Ceiling(office, Some(seal)))
}
pub(crate) fn parse_mcp(value: &str) -> BTreeSet<String> {
if value == "none" {
return BTreeSet::new();
}
value
.split([',', ','])
.map(str::trim)
.filter(|g| !g.is_empty())
.map(str::to_owned)
.collect()
}
pub(crate) fn parse_capabilities(value: &str) -> Result<BTreeSet<Capability>, Box<dyn Error>> {
if value == "none" {
return Ok(BTreeSet::new());
}
Ok(value
.split(',')
.map(str::parse::<Capability>)
.collect::<Result<_, _>>()?)
}