mod artifact;
mod c;
mod markdown;
mod rust;

use crate::model::{ContractRenderRequest, GeneratedBundle, ServiceSummary};
use crate::planner::{build_plan, normalize_type_name, trim_option, ContractPlanError};

pub fn generate_bundle(
    request: &ContractRenderRequest,
) -> Result<GeneratedBundle, ContractPlanError> {
    let plan = build_plan(request)?;
    let mut artifacts = Vec::new();
    let primary_transport = request.transports[0].clone();

    artifacts.extend(c::render_common_c_artifacts(&plan, &primary_transport));
    for transport in &request.transports {
        artifacts.push(markdown::render_markdown_artifact(&plan, transport));
        artifacts.push(rust::render_rust_artifact(&plan, transport));
        artifacts.extend(c::render_transport_c_artifacts(&plan, transport));
    }

    let services = request
        .services
        .iter()
        .map(|service| ServiceSummary {
            api_kind: service.api_kind.as_str().to_string(),
            interface_package: "site.addzero.okmy.dics.generated.modbus".to_string(),
            interface_simple_name: normalize_type_name(&service.interface_name),
            summary: trim_option(&service.interface_summary).unwrap_or_default(),
            operation_count: service.methods.len() as i64,
        })
        .collect::<Vec<_>>();

    Ok(GeneratedBundle {
        summary: format!(
            "已规划 {} 个服务、{} 个文件",
            services.len(),
            artifacts.len()
        ),
        artifacts,
        services,
    })
}
