use std::fs::{self, File};
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use serde::Deserialize;
use serde_json::Value;

use super::string_key;
use crate::telemetry::host::{self as host_telemetry, HostContextSnapshot};

const CLAUDE_CONTEXT_WINDOW_VARS: &[&str] = &[
    "CCD_CLAUDE_CONTEXT_WINDOW_TOKENS",
    "CLAUDE_CONTEXT_WINDOW_TOKENS",
];

pub(crate) fn current(repo_root: &Path) -> Result<Option<HostContextSnapshot>> {
    let project_dir = claude_home()?
        .join("projects")
        .join(project_slug(repo_root));
    if !project_dir.is_dir() {
        return Ok(None);
    }

    let session_id_override =
        host_telemetry::env_string(&["CCD_CLAUDE_SESSION_ID", "CLAUDE_SESSION_ID"]);
    let session_log = match session_id_override.as_deref() {
        Some(session_id) => {
            let path = project_dir.join(format!("{session_id}.jsonl"));
            if path.is_file() {
                Some(path)
            } else {
                None
            }
        }
        None => latest_session_log(&project_dir)?,
    };
    let Some(session_log) = session_log else {
        return Ok(None);
    };

    let observed_at_epoch_s = match host_telemetry::file_mtime_epoch_s(&session_log)? {
        Some(epoch_s) => epoch_s,
        None => return Ok(None),
    };
    if session_id_override.is_none() && !host_telemetry::is_recent(observed_at_epoch_s)? {
        return Ok(None);
    }

    let Some(metrics) = latest_session_metrics(&session_log)? else {
        return Ok(None);
    };
    // Precedence for Claude (no native window source in session logs):
    //   CCD_CLAUDE_CONTEXT_WINDOW_TOKENS / CLAUDE_CONTEXT_WINDOW_TOKENS
    //     -> CCD_CONTEXT_WINDOW_TOKENS (general runtime-agnostic fallback).
    let context_window = host_telemetry::env_u64(CLAUDE_CONTEXT_WINDOW_VARS)
        .or_else(host_telemetry::general_context_window);
    let compacted = session_was_compacted(&project_dir, &session_log, &metrics.session_id)?;

    Ok(Some(HostContextSnapshot {
        host: "claude",
        observed_at_epoch_s,
        model_name: metrics
            .model_name
            .or_else(|| host_telemetry::env_string(&["CCD_CLAUDE_MODEL", "CLAUDE_MODEL"]))
            .or_else(|| host_telemetry::env_string(&["CCD_HOST_MODEL"])),
        context_used_pct: host_telemetry::compute_pct(metrics.latest_prompt_tokens, context_window),
        total_tokens: Some(metrics.latest_prompt_tokens),
        model_context_window: context_window,
        compacted,
        cost_usage: host_telemetry::HostCostUsage {
            input_tokens: metrics.input_tokens,
            output_tokens: metrics.output_tokens,
            cache_creation_input_tokens: metrics.cache_creation_input_tokens,
            cache_read_input_tokens: metrics.cache_read_input_tokens,
            blended_total_tokens: None,
        },
    }))
}

fn claude_home() -> Result<PathBuf> {
    if let Some(path) = host_telemetry::env_string(&["CCD_CLAUDE_HOME", "CLAUDE_HOME"]) {
        return Ok(PathBuf::from(path));
    }

    Ok(host_telemetry::home_dir()?.join(".claude"))
}

fn latest_session_log(project_dir: &Path) -> Result<Option<PathBuf>> {
    let mut newest: Option<(u64, PathBuf)> = None;

    for entry in fs::read_dir(project_dir)
        .with_context(|| format!("failed to read {}", project_dir.display()))?
    {
        let entry =
            entry.with_context(|| format!("failed to read entry in {}", project_dir.display()))?;
        let path = entry.path();
        let is_session_log = path
            .file_name()
            .and_then(|name| name.to_str())
            .map(|name| name.ends_with(".jsonl"))
            .unwrap_or(false);
        if !is_session_log {
            continue;
        }

        let mtime = match host_telemetry::file_mtime_epoch_s(&path)? {
            Some(epoch_s) => epoch_s,
            None => continue,
        };

        match &newest {
            Some((best, _)) if *best >= mtime => {}
            _ => newest = Some((mtime, path)),
        }
    }

    Ok(newest.map(|(_, path)| path))
}

fn latest_session_metrics(path: &Path) -> Result<Option<ClaudeSessionMetrics>> {
    let file = File::open(path).with_context(|| format!("failed to open {}", path.display()))?;
    let reader = BufReader::new(file);
    let mut latest: Option<ClaudeSessionMetrics> = None;

    for line in reader.lines() {
        let line = line.with_context(|| format!("failed to read {}", path.display()))?;
        let value: Value = match serde_json::from_str(&line) {
            Ok(value) => value,
            Err(_) => continue,
        };
        let model_name = string_key(
            &value,
            &["model", "model_name", "modelName", "display_name"],
        );
        let entry: ClaudeSessionEntry = match serde_json::from_value(value) {
            Ok(entry) => entry,
            Err(_) => continue,
        };

        let Some(message) = entry.message else {
            continue;
        };
        let Some(usage) = message.usage else {
            continue;
        };

        let prompt_tokens = usage
            .input_tokens
            .saturating_add(usage.cache_creation_input_tokens)
            .saturating_add(usage.cache_read_input_tokens);
        if prompt_tokens == 0 && usage.output_tokens == 0 {
            continue;
        }

        let Some(session_id) = entry.session_id else {
            continue;
        };

        match &mut latest {
            Some(metrics) => {
                metrics.session_id = session_id;
                metrics.latest_prompt_tokens = prompt_tokens;
                metrics.input_tokens = metrics.input_tokens.saturating_add(usage.input_tokens);
                metrics.output_tokens = metrics.output_tokens.saturating_add(usage.output_tokens);
                metrics.cache_creation_input_tokens = metrics
                    .cache_creation_input_tokens
                    .saturating_add(usage.cache_creation_input_tokens);
                metrics.cache_read_input_tokens = metrics
                    .cache_read_input_tokens
                    .saturating_add(usage.cache_read_input_tokens);
                if model_name.is_some() {
                    metrics.model_name = model_name;
                }
            }
            None => {
                latest = Some(ClaudeSessionMetrics {
                    session_id,
                    latest_prompt_tokens: prompt_tokens,
                    input_tokens: usage.input_tokens,
                    output_tokens: usage.output_tokens,
                    cache_creation_input_tokens: usage.cache_creation_input_tokens,
                    cache_read_input_tokens: usage.cache_read_input_tokens,
                    model_name,
                });
            }
        }
    }

    Ok(latest)
}

fn session_was_compacted(
    project_dir: &Path,
    session_log: &Path,
    session_id: &str,
) -> Result<Option<bool>> {
    let subagents_dir = project_dir.join(session_id).join("subagents");
    if subagents_dir.is_dir() {
        for entry in fs::read_dir(&subagents_dir)
            .with_context(|| format!("failed to read {}", subagents_dir.display()))?
        {
            let entry = entry
                .with_context(|| format!("failed to read entry in {}", subagents_dir.display()))?;
            let path = entry.path();
            let is_acompact = path
                .file_name()
                .and_then(|name| name.to_str())
                .map(|name| name.starts_with("agent-acompact-") && name.ends_with(".jsonl"))
                .unwrap_or(false);
            if is_acompact {
                return Ok(Some(true));
            }
        }
    }

    let contents = fs::read_to_string(session_log)
        .with_context(|| format!("failed to read {}", session_log.display()))?;
    if contents.contains("<command-name>/compact</command-name>") {
        return Ok(Some(true));
    }

    Ok(None)
}

fn project_slug(repo_root: &Path) -> String {
    repo_root
        .canonicalize()
        .unwrap_or_else(|_| repo_root.to_path_buf())
        .to_string_lossy()
        .replace('/', "-")
}

#[derive(Deserialize)]
struct ClaudeSessionEntry {
    #[serde(rename = "sessionId")]
    session_id: Option<String>,
    message: Option<ClaudeMessage>,
}

#[derive(Deserialize)]
struct ClaudeMessage {
    usage: Option<ClaudeUsage>,
}

#[derive(Deserialize)]
struct ClaudeUsage {
    #[serde(default)]
    input_tokens: u64,
    #[serde(default)]
    output_tokens: u64,
    #[serde(default)]
    cache_creation_input_tokens: u64,
    #[serde(default)]
    cache_read_input_tokens: u64,
}

struct ClaudeSessionMetrics {
    session_id: String,
    latest_prompt_tokens: u64,
    input_tokens: u64,
    output_tokens: u64,
    cache_creation_input_tokens: u64,
    cache_read_input_tokens: u64,
    model_name: Option<String>,
}
