//! Initialization and status operations.

use crate::bridge;
use crate::config::AphoriaConfig;
use crate::episteme::{create_authoritative_corpus, LocalEpisteme};
use crate::error::AphoriaError;
use tracing::{info, instrument};

/// Show current scan status.
#[instrument(skip(config))]
pub async fn show_status(config: &AphoriaConfig) -> Result<String, AphoriaError> {
    info!("Showing status");

    let project_root = std::env::current_dir()?;
    let aphoria_dir = project_root.join(".aphoria");
    let data_dir = &config.episteme.data_dir;

    let mut output = String::new();

    if !data_dir.exists() {
        output.push_str("Aphoria status: Not initialized. Run `aphoria init` first.\n");
        return Ok(output);
    }

    output.push_str("Aphoria status:\n");
    output.push_str(&format!("  Data directory: {}\n", data_dir.display()));
    output.push_str(&format!("  Project root: {}\n", project_root.display()));

    if aphoria_dir.join("baseline").exists() {
        let baseline = std::fs::read_to_string(aphoria_dir.join("baseline"))?;
        output.push_str(&format!("  Baseline: {}\n", baseline.trim()));
    } else {
        output.push_str("  Baseline: none\n");
    }

    if aphoria_dir.join("agent.key").exists() {
        output.push_str("  Agent key: present\n");
    } else {
        output.push_str("  Agent key: not generated\n");
    }

    Ok(output)
}

/// Initialize Aphoria with the authoritative corpus.
///
/// Downloads and ingests:
/// - RFC corpus (auth, crypto, TLS)
/// - OWASP cheat sheets
#[instrument(skip(config))]
pub async fn initialize(config: &AphoriaConfig) -> Result<(), AphoriaError> {
    info!("Initializing Aphoria");

    let project_root = std::env::current_dir()?;

    // Create .aphoria directory
    let aphoria_dir = project_root.join(".aphoria");
    std::fs::create_dir_all(&aphoria_dir)?;

    // Open Episteme (this will create the data directory)
    let mut episteme = LocalEpisteme::open(config, &project_root).await?;

    // Generate signing key for authoritative corpus
    let signing_key = bridge::load_or_generate_key(&project_root)?;

    // Create and ingest authoritative corpus
    let corpus = create_authoritative_corpus(&signing_key);
    let ingested = episteme.ingest_authoritative(&corpus).await?;

    episteme.shutdown().await;

    info!(assertions = ingested, "Authoritative corpus ingested");
    Ok(())
}
