use crate::workflow::model::{Task, Workflow};

const SCHEMA: &str = r#"{"tasks":[{"id":"T1","step":1,"title":"short imperative title","decisions":["a decision you made and why"],"acceptance":["a checkable acceptance criterion"],"evidence":["test-output.txt"]}]}"#;

const RULES: &str = "\
How cast runs a workflow:
- Steps run in ascending order. Tasks with the same step number run at the same time, each with its own agent, in the same /work checkout.
- Each agent sees only the original prompt and its own task, so every task must carry the decisions and context it needs.
- The VM has an XFCE desktop on DISPLAY=:0 that all agents share. Visual work is checked there, in real windows, with real screenshots.
- Each task lists the decisions it made, its acceptance criteria and the evidence to attach.
- Evidence is the bare file names the task will write as proof, such as test output, logs or screenshots. Cast picks the folder, so give no directory.

Rules for tasks that run at the same time:
- Read the code to find the files each task will create or change. Tasks in one step must not change the same files, including shared ones such as lockfiles, manifests, generated code, snapshots, docs and changelogs.
- If two tasks need the same files, put them in different steps, or have each work in its own git worktree on its own branch and add a later task that merges them.
- They never commit, stash, reset, rebase, check out or clean, and never revert changes they did not make: another agent may be in the middle of its work.
- They do not run commands that rewrite files they do not own, such as project-wide formatters or code generators.

Rules for git:
- If /work is not a git repository, no task uses git, and parallel tasks keep to separate files.
- Only a task that runs alone in its step commits. When parallel tasks change the project, follow them with a consolidation task that reviews the combined diff, merges any worktree branches, resolves conflicts, runs the full checks and commits the work.
- Group commits by logical change and follow the project's own instructions, such as CLAUDE.md, AGENTS.md or CONTRIBUTING.md, on commits and checks.
- A task that adds worktrees removes them once its branch is merged.";

pub fn workflow(prompt: &str, prior: Option<(&Workflow, &str)>) -> String {
    let mut out = format!(
        "You plan software work. The working directory /work is the user's project; read it as needed but do not change any files.\n\
         Turn the user's prompt below into a workflow of tasks.\n\n{RULES}\n\n\
         Answer with only JSON matching this shape, no prose and no code fence:\n{SCHEMA}\n\n<prompt>\n{prompt}\n</prompt>\n"
    );
    if let Some((wf, feedback)) = prior {
        out += &format!(
            "\nThis is the current workflow:\n{}\n\nRevise it with this feedback:\n{feedback}\n",
            json(wf)
        );
    }
    out
}

pub fn check(prompt: &str, draft: &Workflow) -> String {
    format!(
        "You review a workflow that another agent planned from the user's prompt. The working directory /work is the user's project; read it as needed but do not change any files.\n\
         Make sure the workflow is ready to run and correct, and fix it where it is not.\n\n{RULES}\n\n\
         Check each of these against the prompt and the code:\n\
         - It does everything the prompt asks and nothing it does not.\n\
         - Tasks in the same step change separate files. Open the files to confirm it.\n\
         - Each task depends only on tasks in earlier steps.\n\
         - Commits come only from tasks that run alone, and parallel work is consolidated before anything builds on it.\n\
         - Every acceptance criterion can be checked by running something or reading the evidence.\n\
         - Every task has the decisions and context its agent needs without seeing the other tasks.\n\n\
         Answer with only JSON, no prose and no code fence: the corrected workflow in this shape, plus \"changes\", a list with one short sentence for each change you made and why. Leave \"changes\" empty if the workflow was already right.\n\
         {SCHEMA}\n\n<prompt>\n{prompt}\n</prompt>\n\n<workflow>\n{}\n</workflow>\n",
        json(draft)
    )
}

fn json(wf: &Workflow) -> String {
    serde_json::to_string_pretty(&wf.tasks).unwrap_or_default()
}

pub fn assist(doc: &str, range: (usize, usize), instruction: &str) -> String {
    let (a, b) = range;
    let doc = format!("{}<<<{}>>>{}", &doc[..a], &doc[a..b], &doc[b..]);
    let task = if a == b {
        "Write new markdown to insert at the <<<>>> marker."
    } else {
        "Rewrite the markdown between <<< and >>>."
    };
    format!(
        "You help write a markdown prompt document. Do not use tools.\n{task}\nInstruction: {instruction}\n\
         Answer with only the replacement markdown, without the markers, without a code fence and without commentary.\n\n<document>\n{doc}\n</document>\n"
    )
}

pub fn task(wf: &Workflow, task: &Task, evidence_dir: &str, prompt: &str) -> String {
    let list = |xs: &[String]| xs.iter().map(|x| format!("- {x}\n")).collect::<String>();
    let others: Vec<String> = wf
        .tasks
        .iter()
        .filter(|t| t.step == task.step && t.id != task.id)
        .map(|t| format!("{}: {}", t.id, t.title))
        .collect();
    let parallel = if others.is_empty() {
        String::new()
    } else {
        format!(
            "\nThese tasks run at the same time as yours, each with its own agent, in the same /work:\n{}\
             Change only the files your task needs. Do not commit, stash, reset, rebase, check out or clean, do not revert changes you did not make, and do not run project-wide formatters or generators. If your task says to use a git worktree, work only inside it.\n\
             The other agents share the desktop with you: find your windows by the PID you started, never close or type into windows you did not open, and give agent-browser a --session of your own.\n",
            list(&others)
        )
    };
    format!(
        "You are running task {id} of a workflow in /work, the user's project.\n\
         Original prompt:\n<prompt>\n{prompt}\n</prompt>\n\n\
         Task {id}: {title}\nDecisions already made:\n{d}\nAcceptance criteria:\n{a}\nEvidence to attach:\n{e}{parallel}\n\
         The VM runs an XFCE desktop on DISPLAY=:0 at 1280x800, and agent-browser opens real windows on it. Look at and use visual work there as a person would, and follow the xfce-computer-use skill to drive and capture it.\n\
         Do the work. Save every piece of evidence into {evidence_dir}/ (create it).\n\
         Finish with a short summary of what changed and how each acceptance criterion was met.\n\
         Workflow {name} v{v}, step {step} of {steps}.\n",
        id = task.id,
        title = task.title,
        d = list(&task.decisions),
        a = list(&task.acceptance),
        e = list(&task.evidence),
        name = wf.prompt,
        v = wf.version,
        step = task.step,
        steps = wf.steps().len(),
    )
}

#[cfg(test)]
mod tests {
    use crate::workflow::model::{Task, Workflow};

    #[test]
    fn a_task_prompt_names_only_the_tasks_running_beside_it() {
        let task = |id: &str, step, title: &str| Task {
            id: id.into(),
            step,
            title: title.into(),
            ..Task::default()
        };
        let wf = Workflow {
            tasks: vec![
                task("T1", 1, "api"),
                task("T2", 1, "ui"),
                task("T3", 2, "merge"),
            ],
            ..Workflow::default()
        };
        let p = super::task(&wf, &wf.tasks[0], "/cast/runs/x/T1", "go");
        assert!(p.contains("T2: ui") && !p.contains("T3: merge") && p.contains("Do not commit"));
        let alone = super::task(&wf, &wf.tasks[2], "/cast/runs/x/T3", "go");
        assert!(!alone.contains("Do not commit"));
    }
}
