offline-cli 0.4.0

The Offline Protocol developer CLI
//! `offline init`: add offline.config.json, AGENTS.md, and .mcp.json to an existing app.
//! Works in JavaScript/TypeScript projects (package.json) and in Python, Swift
//! and Gradle (Kotlin or Java) projects. An existing `.mcp.json` is never modified.

use std::path::PathBuf;

use anyhow::{bail, Result};
use clap::Args;
use offline_generator::project_detect::{self, NativeProject};
use offline_generator::project_wiring::{self, McpRegistration};
use offline_registry::Registry;
use serde_json::json;

use crate::config::CliConfig;
use crate::output;

#[derive(Args)]
pub struct InitArgs {
    /// Project directory (defaults to current directory). JavaScript/TypeScript
    /// (package.json), Python (pyproject.toml, requirements.txt, setup.py),
    /// Swift (Package.swift, .xcodeproj) and Gradle (Kotlin or Java) projects
    #[arg(long, default_value = ".")]
    pub dir: PathBuf,
    /// Offline application ID (defaults to the value from `offline login` / `offline setup`)
    #[arg(long)]
    pub app_id: Option<String>,
    /// Output JSON
    #[arg(long)]
    pub json: bool,
}

pub fn run(args: InitArgs) -> Result<()> {
    let dir = &args.dir;
    let pkg_path = dir.join("package.json");
    let app_id = args
        .app_id
        .or_else(|| CliConfig::load().ok().and_then(|c| c.effective_app_id()))
        .unwrap_or_default();
    let registry = Registry::load_default()?;

    let (project_name, platform, installed, native) = if pkg_path.exists() {
        let pkg: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&pkg_path)?)?;
        let deps = collect_deps(&pkg);
        let platform = detect_platform(&deps).to_string();
        let project_name = pkg
            .get("name")
            .and_then(|n| n.as_str())
            .unwrap_or("offline-app")
            .to_string();
        let installed: Vec<String> = registry
            .packages()
            .filter(|p| deps.iter().any(|d| d == &p.name))
            .map(|p| p.name.clone())
            .collect();
        (project_name, platform, installed, None)
    } else if let Some(project) = project_detect::detect_native(dir) {
        let installed = project.installed_packages(&registry);
        (
            project.name.clone(),
            project.platform.to_string(),
            installed,
            Some(project),
        )
    } else {
        bail!("{}", project_detect::unsupported_message(dir));
    };

    let mut written = Vec::new();

    let config_path = dir.join("offline.config.json");
    if config_path.exists() {
        output::warn("offline.config.json already exists — leaving it untouched");
    } else {
        let config = json!({
            "$schema": "https://dev.offlineprotocol.com/schemas/offline.config.json",
            "projectName": project_name,
            "appId": app_id,
            "platform": platform,
            "packages": installed,
        });
        std::fs::write(&config_path, serde_json::to_string_pretty(&config)?)?;
        written.push("offline.config.json");
    }

    let mcp_path = dir.join(".mcp.json");
    let registration = if mcp_path.exists() {
        if project_wiring::registers_offline_mcp(&std::fs::read_to_string(&mcp_path)?) {
            McpRegistration::AlreadyRegistered
        } else {
            output::warn(&format!(
                ".mcp.json already exists and does not register the Offline Protocol MCP server; \
left it unchanged. Add `{}` to your agent (see `offline mcp install`) or use the Offline Protocol plugin.",
                offline_registry::mcp_serve_command_line()
            ));
            McpRegistration::NotRegistered
        }
    } else {
        std::fs::write(
            &mcp_path,
            serde_json::to_string_pretty(&project_wiring::mcp_json())? + "\n",
        )?;
        written.push(".mcp.json");
        McpRegistration::Written
    };

    let agents_path = dir.join("AGENTS.md");
    // A native project without the SDK yet still gets the skills of the SDK
    // it will add, so an agent reads the right guide first.
    let sdk_skills = native
        .as_ref()
        .filter(|_| installed.is_empty())
        .and_then(|p| p.sdk_package(&registry))
        .map(|sdk| sdk.skills.clone())
        .unwrap_or_default();
    let skills: Vec<String> = registry
        .packages()
        .filter(|p| installed.contains(&p.name))
        .flat_map(|p| p.skills.clone())
        .chain(sdk_skills)
        .collect::<std::collections::BTreeSet<_>>()
        .into_iter()
        .collect();
    let section = project_wiring::agents_section(&installed, &skills, registration);
    if agents_path.exists() {
        let existing = std::fs::read_to_string(&agents_path)?;
        if project_wiring::agents_has_section(&existing) {
            output::warn("AGENTS.md already has an Offline Protocol section; skipping");
        } else {
            std::fs::write(&agents_path, format!("{existing}\n{section}"))?;
            written.push("AGENTS.md (appended)");
        }
    } else {
        std::fs::write(&agents_path, format!("# Agent guide\n{section}"))?;
        written.push("AGENTS.md");
    }

    if args.json {
        return output::json(&json!({
            "dir": dir,
            "platform": platform,
            "detectedPackages": installed,
            "filesWritten": written,
            "nextSteps": native.as_ref().map(|p| next_steps(p, &registry, &installed)),
        }));
    }
    output::success(&format!(
        "Initialized Offline Protocol wiring in {} ({})",
        dir.display(),
        platform
    ));
    for w in &written {
        output::item(w, "");
    }
    match &native {
        Some(project) => {
            if installed.is_empty() {
                if let Some(sdk) = project.sdk_package(&registry) {
                    output::note(&format!(
                        "no Offline Protocol SDK found in this {} project yet — add it with: {}",
                        project.language,
                        project.install_hint(sdk)
                    ));
                }
            }
            output::note(&format!(
                "{} guide: {}",
                project.language,
                project.docs_url()
            ));
        }
        None if installed.is_empty() => output::note(
            "no @offline-protocol packages detected yet — add one with `offline add <package>`",
        ),
        None => {}
    }
    Ok(())
}

/// Install line (when the SDK is missing) and docs link for a non-JS project.
fn next_steps(
    project: &NativeProject,
    registry: &Registry,
    installed: &[String],
) -> serde_json::Value {
    let install = if installed.is_empty() {
        project
            .sdk_package(registry)
            .map(|sdk| project.install_hint(sdk))
    } else {
        None
    };
    json!({
        "language": project.language,
        "install": install,
        "docs": project.docs_url(),
    })
}

fn collect_deps(pkg: &serde_json::Value) -> Vec<String> {
    let mut out = Vec::new();
    for key in ["dependencies", "devDependencies", "peerDependencies"] {
        if let Some(map) = pkg.get(key).and_then(|d| d.as_object()) {
            out.extend(map.keys().cloned());
        }
    }
    out
}

fn detect_platform(deps: &[String]) -> &'static str {
    if deps.iter().any(|d| d == "react-native") {
        "react-native"
    } else if deps.iter().any(|d| d == "next") {
        "nextjs"
    } else if deps.iter().any(|d| d == "react") {
        "web"
    } else {
        "unknown"
    }
}