pub fn print_sync(
    result: &SyncResult,
    elapsed: std::time::Duration,
    metrics: Option<&MetricsLayer>,
    show_timings: bool,
) {
    let has_data = result.issues_updated > 0
        || result.mrs_updated > 0
        || result.discussions_fetched > 0
        || result.resource_events_fetched > 0
        || result.mr_diffs_fetched > 0
        || result.documents_regenerated > 0
        || result.documents_embedded > 0
        || result.statuses_enriched > 0;
    let has_failures = result.resource_events_failed > 0
        || result.mr_diffs_failed > 0
        || result.status_enrichment_errors > 0
        || result.documents_errored > 0
        || result.embedding_failed > 0;

    if !has_data && !has_failures {
        println!(
            "\n  {} ({})\n",
            Theme::dim().render("Already up to date"),
            Theme::timing().render(&format!("{:.1}s", elapsed.as_secs_f64()))
        );
    } else {
        let headline = if has_failures {
            Theme::warning().bold().render("Sync completed with issues")
        } else {
            Theme::success().bold().render("Synced")
        };
        println!(
            "\n  {} {} issues and {} MRs in {}",
            headline,
            Theme::info()
                .bold()
                .render(&result.issues_updated.to_string()),
            Theme::info().bold().render(&result.mrs_updated.to_string()),
            Theme::timing().render(&format!("{:.1}s", elapsed.as_secs_f64()))
        );

        // Detail: supporting counts, compact middle-dot format, zero-suppressed
        let mut details: Vec<String> = Vec::new();
        if result.discussions_fetched > 0 {
            details.push(format!(
                "{} {}",
                Theme::info().render(&result.discussions_fetched.to_string()),
                Theme::dim().render("discussions")
            ));
        }
        if result.resource_events_fetched > 0 {
            details.push(format!(
                "{} {}",
                Theme::info().render(&result.resource_events_fetched.to_string()),
                Theme::dim().render("events")
            ));
        }
        if result.mr_diffs_fetched > 0 {
            details.push(format!(
                "{} {}",
                Theme::info().render(&result.mr_diffs_fetched.to_string()),
                Theme::dim().render("diffs")
            ));
        }
        if result.statuses_enriched > 0 {
            details.push(format!(
                "{} {}",
                Theme::info().render(&result.statuses_enriched.to_string()),
                Theme::dim().render("statuses updated")
            ));
        }
        if !details.is_empty() {
            let sep = Theme::dim().render(" \u{b7} ");
            println!("  {}", details.join(&sep));
        }

        // Documents: regeneration + embedding as a second detail line
        let mut doc_parts: Vec<String> = Vec::new();
        if result.documents_regenerated > 0 {
            doc_parts.push(format!(
                "{} {}",
                Theme::info().render(&result.documents_regenerated.to_string()),
                Theme::dim().render("docs regenerated")
            ));
        }
        if result.documents_embedded > 0 {
            doc_parts.push(format!(
                "{} {}",
                Theme::info().render(&result.documents_embedded.to_string()),
                Theme::dim().render("embedded")
            ));
        }
        if result.documents_errored > 0 {
            doc_parts
                .push(Theme::error().render(&format!("{} doc errors", result.documents_errored)));
        }
        if !doc_parts.is_empty() {
            let sep = Theme::dim().render(" \u{b7} ");
            println!("  {}", doc_parts.join(&sep));
        }

        // Errors: visually prominent, only if non-zero
        let mut errors: Vec<String> = Vec::new();
        if result.resource_events_failed > 0 {
            errors.push(format!("{} event failures", result.resource_events_failed));
        }
        if result.mr_diffs_failed > 0 {
            errors.push(format!("{} diff failures", result.mr_diffs_failed));
        }
        if result.status_enrichment_errors > 0 {
            errors.push(format!("{} status errors", result.status_enrichment_errors));
        }
        if result.embedding_failed > 0 {
            errors.push(format!("{} embedding failures", result.embedding_failed));
        }
        if !errors.is_empty() {
            println!("  {}", Theme::error().render(&errors.join(" \u{b7} ")));
        }

        println!();
    }

    if let Some(metrics) = metrics {
        let stages = metrics.extract_timings();
        if should_print_timings(show_timings, &stages) {
            print_timing_summary(&stages);
        }
    }
}

fn issue_sub_rows(projects: &[ProjectSummary]) -> Vec<String> {
    projects
        .iter()
        .map(|p| {
            let mut parts: Vec<String> = Vec::new();
            parts.push(format!(
                "{} {}",
                p.items_upserted,
                if p.items_upserted == 1 {
                    "issue"
                } else {
                    "issues"
                }
            ));
            if p.discussions_synced > 0 {
                parts.push(format!("{} discussions", p.discussions_synced));
            }
            if p.statuses_seen > 0 || p.statuses_enriched > 0 {
                parts.push(format!("{} statuses updated", p.statuses_enriched));
            }
            if p.events_fetched > 0 {
                parts.push(format!("{} events", p.events_fetched));
            }
            if p.status_errors > 0 {
                parts.push(Theme::warning().render(&format!("{} status errors", p.status_errors)));
            }
            if p.events_failed > 0 {
                parts.push(Theme::warning().render(&format!("{} event failures", p.events_failed)));
            }
            let sep = Theme::dim().render(" \u{b7} ");
            let detail = parts.join(&sep);
            let path = Theme::muted().render(&format!("{:<30}", p.path));
            format!("      {path} {detail}")
        })
        .collect()
}

fn status_sub_rows(projects: &[ProjectStatusEnrichment]) -> Vec<String> {
    projects
        .iter()
        .map(|p| {
            let total_errors = p.partial_errors + usize::from(p.error.is_some());
            let mut parts: Vec<String> = vec![format!("{} statuses updated", p.enriched)];
            if p.cleared > 0 {
                parts.push(format!("{} cleared", p.cleared));
            }
            if p.seen > 0 {
                parts.push(format!("{} seen", p.seen));
            }
            if total_errors > 0 {
                parts.push(Theme::warning().render(&format!("{} errors", total_errors)));
            } else if p.mode == "skipped" {
                if let Some(reason) = &p.reason {
                    parts.push(Theme::dim().render(&format!("skipped ({reason})")));
                } else {
                    parts.push(Theme::dim().render("skipped"));
                }
            }
            let sep = Theme::dim().render(" \u{b7} ");
            let detail = parts.join(&sep);
            let path = Theme::muted().render(&format!("{:<30}", p.path));
            format!("      {path} {detail}")
        })
        .collect()
}

fn mr_sub_rows(projects: &[ProjectSummary]) -> Vec<String> {
    projects
        .iter()
        .map(|p| {
            let mut parts: Vec<String> = Vec::new();
            parts.push(format!(
                "{} {}",
                p.items_upserted,
                if p.items_upserted == 1 { "MR" } else { "MRs" }
            ));
            if p.discussions_synced > 0 {
                parts.push(format!("{} discussions", p.discussions_synced));
            }
            if p.mr_diffs_fetched > 0 {
                parts.push(format!("{} diffs", p.mr_diffs_fetched));
            }
            if p.events_fetched > 0 {
                parts.push(format!("{} events", p.events_fetched));
            }
            if p.mr_diffs_failed > 0 {
                parts
                    .push(Theme::warning().render(&format!("{} diff failures", p.mr_diffs_failed)));
            }
            if p.events_failed > 0 {
                parts.push(Theme::warning().render(&format!("{} event failures", p.events_failed)));
            }
            let sep = Theme::dim().render(" \u{b7} ");
            let detail = parts.join(&sep);
            let path = Theme::muted().render(&format!("{:<30}", p.path));
            format!("      {path} {detail}")
        })
        .collect()
}

fn emit_stage_line(
    pb: &indicatif::ProgressBar,
    icon: &str,
    label: &str,
    summary: &str,
    elapsed: std::time::Duration,
) {
    pb.finish_and_clear();
    print_static_lines(&[format_stage_line(icon, label, summary, elapsed)]);
}

fn emit_stage_block(
    pb: &indicatif::ProgressBar,
    icon: &str,
    label: &str,
    summary: &str,
    elapsed: std::time::Duration,
    sub_rows: &[String],
) {
    pb.finish_and_clear();
    let mut lines = Vec::with_capacity(1 + sub_rows.len());
    lines.push(format_stage_line(icon, label, summary, elapsed));
    lines.extend(sub_rows.iter().cloned());
    print_static_lines(&lines);
}

fn print_static_lines(lines: &[String]) {
    crate::cli::progress::multi().suspend(|| {
        for line in lines {
            println!("{line}");
        }
    });
}

fn should_print_timings(show_timings: bool, stages: &[StageTiming]) -> bool {
    show_timings && !stages.is_empty()
}

fn append_failures(summary: &mut String, failures: &[(&str, usize)]) {
    let rendered: Vec<String> = failures
        .iter()
        .filter_map(|(label, count)| {
            (*count > 0).then_some(Theme::warning().render(&format!("{count} {label}")))
        })
        .collect();
    if !rendered.is_empty() {
        summary.push_str(&format!(" ({})", rendered.join(", ")));
    }
}

fn summarize_status_enrichment(projects: &[ProjectStatusEnrichment]) -> (String, bool) {
    let statuses_enriched: usize = projects.iter().map(|p| p.enriched).sum();
    let statuses_seen: usize = projects.iter().map(|p| p.seen).sum();
    let statuses_cleared: usize = projects.iter().map(|p| p.cleared).sum();
    let status_errors: usize = projects
        .iter()
        .map(|p| p.partial_errors + usize::from(p.error.is_some()))
        .sum();
    let skipped = projects.iter().filter(|p| p.mode == "skipped").count();

    let mut parts = vec![format!(
        "{} statuses updated",
        format_number(statuses_enriched as i64)
    )];
    if statuses_cleared > 0 {
        parts.push(format!(
            "{} cleared",
            format_number(statuses_cleared as i64)
        ));
    }
    if statuses_seen > 0 {
        parts.push(format!("{} seen", format_number(statuses_seen as i64)));
    }
    if status_errors > 0 {
        parts.push(format!("{} errors", format_number(status_errors as i64)));
    } else if projects.is_empty() || skipped == projects.len() {
        parts.push("skipped".to_string());
    }

    (parts.join(" \u{b7} "), status_errors > 0)
}

fn section(title: &str) {
    println!("{}", render::section_divider(title));
}

fn print_timing_summary(stages: &[StageTiming]) {
    section("Timing");
    for stage in stages {
        for sub in &stage.sub_stages {
            print_stage_line(sub, 1);
        }
    }
}

fn print_stage_line(stage: &StageTiming, depth: usize) {
    let indent = "  ".repeat(depth);
    let name = if let Some(ref project) = stage.project {
        format!("{} ({})", stage.name, project)
    } else {
        stage.name.clone()
    };
    let pad_width = 30_usize.saturating_sub(indent.len() + name.len());
    let dots = Theme::dim().render(&".".repeat(pad_width.max(2)));

    let time_str = Theme::bold().render(&format!("{:.1}s", stage.elapsed_ms as f64 / 1000.0));

    let mut parts: Vec<String> = Vec::new();
    if stage.items_processed > 0 {
        parts.push(format!("{} items", stage.items_processed));
    }
    if stage.errors > 0 {
        parts.push(Theme::error().render(&format!("{} errors", stage.errors)));
    }
    if stage.rate_limit_hits > 0 {
        parts.push(Theme::warning().render(&format!("{} rate limits", stage.rate_limit_hits)));
    }

    if parts.is_empty() {
        println!("{indent}{name} {dots} {time_str}");
    } else {
        let suffix = parts.join(" \u{b7} ");
        println!("{indent}{name} {dots} {time_str} ({suffix})");
    }

    for sub in &stage.sub_stages {
        print_stage_line(sub, depth + 1);
    }
}

#[derive(Serialize)]
struct SyncJsonOutput<'a> {
    ok: bool,
    data: &'a SyncResult,
    meta: SyncMeta,
}

#[derive(Serialize)]
struct SyncMeta {
    run_id: String,
    elapsed_ms: u64,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    stages: Vec<StageTiming>,
}

pub fn print_sync_json(result: &SyncResult, elapsed_ms: u64, metrics: Option<&MetricsLayer>) {
    let stages = metrics.map_or_else(Vec::new, MetricsLayer::extract_timings);
    let output = SyncJsonOutput {
        ok: true,
        data: result,
        meta: SyncMeta {
            run_id: result.run_id.clone(),
            elapsed_ms,
            stages,
        },
    };
    match serde_json::to_string(&output) {
        Ok(json) => println!("{json}"),
        Err(e) => eprintln!("Error serializing to JSON: {e}"),
    }
}

#[derive(Debug, Default, Serialize)]
pub struct SyncDryRunResult {
    pub issues_preview: DryRunPreview,
    pub mrs_preview: DryRunPreview,
    pub would_generate_docs: bool,
    pub would_embed: bool,
}

async fn run_sync_dry_run(config: &Config, options: &SyncOptions) -> Result<SyncResult> {
    // Get dry run previews for both issues and MRs
    let issues_preview = run_ingest_dry_run(config, "issues", None, options.full)?;
    let mrs_preview = run_ingest_dry_run(config, "mrs", None, options.full)?;

    let dry_result = SyncDryRunResult {
        issues_preview,
        mrs_preview,
        would_generate_docs: !options.no_docs,
        would_embed: !options.no_embed,
    };

    if options.robot_mode {
        print_sync_dry_run_json(&dry_result);
    } else {
        print_sync_dry_run(&dry_result);
    }

    // Return an empty SyncResult since this is just a preview
    Ok(SyncResult::default())
}

pub fn print_sync_dry_run(result: &SyncDryRunResult) {
    println!(
        "\n  {} {}",
        Theme::info().bold().render("Dry run"),
        Theme::dim().render("(no changes will be made)")
    );

    print_dry_run_entity("Issues", &result.issues_preview);
    print_dry_run_entity("Merge Requests", &result.mrs_preview);

    // Pipeline stages
    section("Pipeline");
    let mut stages: Vec<String> = Vec::new();
    if result.would_generate_docs {
        stages.push("generate-docs".to_string());
    } else {
        stages.push(Theme::dim().render("generate-docs (skip)"));
    }
    if result.would_embed {
        stages.push("embed".to_string());
    } else {
        stages.push(Theme::dim().render("embed (skip)"));
    }
    println!("  {}", stages.join(" \u{b7} "));
}

fn print_dry_run_entity(label: &str, preview: &DryRunPreview) {
    section(label);
    let mode = if preview.sync_mode == "full" {
        Theme::warning().render("full")
    } else {
        Theme::success().render("incremental")
    };
    println!("  {} \u{b7} {} projects", mode, preview.projects.len());
    for project in &preview.projects {
        let sync_status = if !project.has_cursor {
            Theme::warning().render("initial sync")
        } else {
            Theme::success().render("incremental")
        };
        if project.existing_count > 0 {
            println!(
                "    {} \u{b7} {} \u{b7} {} existing",
                &project.path, sync_status, project.existing_count
            );
        } else {
            println!("    {} \u{b7} {}", &project.path, sync_status);
        }
    }
}

#[derive(Serialize)]
struct SyncDryRunJsonOutput {
    ok: bool,
    dry_run: bool,
    data: SyncDryRunJsonData,
}

#[derive(Serialize)]
struct SyncDryRunJsonData {
    stages: Vec<SyncDryRunStage>,
}

#[derive(Serialize)]
struct SyncDryRunStage {
    name: String,
    would_run: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    preview: Option<DryRunPreview>,
}

pub fn print_sync_dry_run_json(result: &SyncDryRunResult) {
    let output = SyncDryRunJsonOutput {
        ok: true,
        dry_run: true,
        data: SyncDryRunJsonData {
            stages: vec![
                SyncDryRunStage {
                    name: "ingest_issues".to_string(),
                    would_run: true,
                    preview: Some(result.issues_preview.clone()),
                },
                SyncDryRunStage {
                    name: "ingest_mrs".to_string(),
                    would_run: true,
                    preview: Some(result.mrs_preview.clone()),
                },
                SyncDryRunStage {
                    name: "generate_docs".to_string(),
                    would_run: result.would_generate_docs,
                    preview: None,
                },
                SyncDryRunStage {
                    name: "embed".to_string(),
                    would_run: result.would_embed,
                    preview: None,
                },
            ],
        },
    };

    match serde_json::to_string(&output) {
        Ok(json) => println!("{json}"),
        Err(e) => eprintln!("Error serializing to JSON: {e}"),
    }
}

#[cfg(test)]
#[path = "sync_tests.rs"]
mod tests;
