// SPDX-License-Identifier: MIT
// Copyright (c) 2025-2026 SenWeaverCoding
// Licensed under the MIT License.
use super::types::{BudgetCheck, CostRecord, CostSummary, ModelStats, TokenUsage, UsagePeriod};
use crate::config::schema::CostConfig;
use anyhow::{Context, Result, anyhow};
use chrono::{Datelike, NaiveDate, Utc};
use parking_lot::{Mutex, MutexGuard, RwLock};
use std::collections::HashMap;
use std::fs::{self, File, OpenOptions};
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock};

pub struct CostTracker {
    config: CostConfig,
    storage: Arc<Mutex<CostStorage>>,
    session_id: String,
    session_costs: Arc<Mutex<Vec<CostRecord>>>,
}

impl CostTracker {

    pub fn new(config: CostConfig, workspace_dir: &Path) -> Result<Self> {
        let storage_path = resolve_storage_path(workspace_dir)?;

        let storage = CostStorage::new(&storage_path).with_context(|| {
            format!("Failed to open cost storage at {}", storage_path.display())
        })?;

        Ok(Self {
            config,
            storage: Arc::new(Mutex::new(storage)),
            session_id: uuid::Uuid::new_v4().to_string(),
            session_costs: Arc::new(Mutex::new(Vec::new())),
        })
    }

    pub fn session_id(&self) -> &str {
        &self.session_id
    }

    fn lock_storage(&self) -> MutexGuard<'_, CostStorage> {
        self.storage.lock()
    }

    fn lock_session_costs(&self) -> MutexGuard<'_, Vec<CostRecord>> {
        self.session_costs.lock()
    }

    pub fn check_budget(&self, estimated_cost_usd: f64) -> Result<BudgetCheck> {
        if !self.config.enabled {
            return Ok(BudgetCheck::Allowed);
        }

        if !estimated_cost_usd.is_finite() || estimated_cost_usd < 0.0 {
            return Err(anyhow!(
                "Estimated cost must be a finite, non-negative value"
            ));
        }

        let mut storage = self.lock_storage();
        let (daily_cost, monthly_cost) = storage.get_aggregated_costs()?;

        let projected_daily = daily_cost + estimated_cost_usd;
        if projected_daily > self.config.daily_limit_usd {
            return Ok(BudgetCheck::Exceeded {
                current_usd: daily_cost,
                limit_usd: self.config.daily_limit_usd,
                period: UsagePeriod::Day,
            });
        }

        let projected_monthly = monthly_cost + estimated_cost_usd;
        if projected_monthly > self.config.monthly_limit_usd {
            return Ok(BudgetCheck::Exceeded {
                current_usd: monthly_cost,
                limit_usd: self.config.monthly_limit_usd,
                period: UsagePeriod::Month,
            });
        }

        let warn_threshold = f64::from(self.config.warn_at_percent.min(100)) / 100.0;
        let daily_warn_threshold = self.config.daily_limit_usd * warn_threshold;
        let monthly_warn_threshold = self.config.monthly_limit_usd * warn_threshold;

        if projected_daily >= daily_warn_threshold {
            return Ok(BudgetCheck::Warning {
                current_usd: daily_cost,
                limit_usd: self.config.daily_limit_usd,
                period: UsagePeriod::Day,
            });
        }

        if projected_monthly >= monthly_warn_threshold {
            return Ok(BudgetCheck::Warning {
                current_usd: monthly_cost,
                limit_usd: self.config.monthly_limit_usd,
                period: UsagePeriod::Month,
            });
        }

        Ok(BudgetCheck::Allowed)
    }

    pub fn record_usage(&self, usage: TokenUsage) -> Result<()> {
        self.record_usage_for_session_with_mode(None, None, usage)
    }

    pub fn record_usage_for_session(
        &self,
        chat_session_id: Option<&str>,
        usage: TokenUsage,
    ) -> Result<()> {
        self.record_usage_for_session_with_mode(chat_session_id, None, usage)
    }

    pub fn record_usage_for_session_with_mode(
        &self,
        chat_session_id: Option<&str>,
        coding_mode: Option<&str>,
        usage: TokenUsage,
    ) -> Result<()> {
        self.record_usage_with_attribution(chat_session_id, coding_mode, None, usage)
    }

    pub fn record_usage_with_attribution(
        &self,
        chat_session_id: Option<&str>,
        coding_mode: Option<&str>,
        provider: Option<&str>,
        usage: TokenUsage,
    ) -> Result<()> {
        if !self.config.enabled {
            return Ok(());
        }

        if !usage.cost_usd.is_finite() || usage.cost_usd < 0.0 {
            return Err(anyhow!(
                "Token usage cost must be a finite, non-negative value"
            ));
        }

        let record = CostRecord::with_attribution(
            &self.session_id,
            chat_session_id.map(|s| s.to_string()),
            coding_mode.map(|s| s.to_string()),
            provider
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .map(|s| s.to_string()),
            usage,
        );

        {
            let mut storage = self.lock_storage();
            storage.add_record(record.clone())?;
        }

        {
            let mut session_costs = self.lock_session_costs();
            session_costs.push(record.clone());
        }

        fire_usage_notify(&record);

        Ok(())
    }

    pub fn cost_for_chat_session(&self, chat_session_id: &str) -> f64 {
        let session_costs = self.lock_session_costs();
        session_costs
            .iter()
            .filter(|record| {
                record
                    .chat_session_id
                    .as_deref()
                    .map(|sid| sid == chat_session_id)
                    .unwrap_or(false)
            })
            .map(|record| record.usage.cost_usd)
            .sum()
    }

    pub fn get_summary(&self) -> Result<CostSummary> {
        let (daily_cost, monthly_cost) = {
            let mut storage = self.lock_storage();
            storage.get_aggregated_costs()?
        };

        let session_costs = self.lock_session_costs();
        let session_cost: f64 = session_costs
            .iter()
            .map(|record| record.usage.cost_usd)
            .sum();
        let total_tokens: u64 = session_costs
            .iter()
            .map(|record| record.usage.total_tokens)
            .sum();
        let request_count = session_costs.len();
        let by_model = build_session_model_stats(&session_costs);

        Ok(CostSummary {
            session_cost_usd: session_cost,
            daily_cost_usd: daily_cost,
            monthly_cost_usd: monthly_cost,
            total_tokens,
            request_count,
            by_model,
        })
    }

    pub fn get_daily_cost(&self, date: NaiveDate) -> Result<f64> {
        let storage = self.lock_storage();
        storage.get_cost_for_date(date)
    }

    pub fn get_monthly_cost(&self, year: i32, month: u32) -> Result<f64> {
        let storage = self.lock_storage();
        storage.get_cost_for_month(year, month)
    }
}

static GLOBAL_COST_TRACKER: OnceLock<RwLock<Option<Arc<CostTracker>>>> = OnceLock::new();

fn global_cost_tracker_slot() -> &'static RwLock<Option<Arc<CostTracker>>> {
    GLOBAL_COST_TRACKER.get_or_init(|| RwLock::new(None))
}

pub type UsageNotifyCallback = Arc<dyn Fn(&CostRecord) + Send + Sync + 'static>;

static USAGE_NOTIFY_CALLBACK: OnceLock<UsageNotifyCallback> = OnceLock::new();

pub fn set_usage_notify_callback<F>(cb: F)
where
    F: Fn(&CostRecord) + Send + Sync + 'static,
{
    let _ = USAGE_NOTIFY_CALLBACK.set(Arc::new(cb));
}

pub(crate) fn fire_usage_notify(record: &CostRecord) {
    if let Some(cb) = USAGE_NOTIFY_CALLBACK.get() {
        cb(record);
    }
}

impl CostTracker {

    pub fn get_or_init_global(config: CostConfig, workspace_dir: &Path) -> Option<Arc<Self>> {
        let slot = global_cost_tracker_slot();
        if let Some(existing) = slot.read().clone() {
            return Some(existing);
        }
        let mut guard = slot.write();
        if let Some(existing) = guard.as_ref() {
            return Some(existing.clone());
        }
        if !config.enabled {
            return None;
        }
        match Self::new(config, workspace_dir) {
            Ok(ct) => {
                let arc = Arc::new(ct);
                *guard = Some(Arc::clone(&arc));
                Some(arc)
            }
            Err(e) => {
                tracing::warn!("Failed to initialize global cost tracker: {e}");
                None
            }
        }
    }

    pub fn reconfigure_global(config: CostConfig, workspace_dir: &Path) -> Option<Arc<Self>> {
        let slot = global_cost_tracker_slot();
        let mut guard = slot.write();
        if !config.enabled {
            *guard = None;
            return None;
        }
        if let Some(existing) = guard.as_ref() {
            return Some(existing.clone());
        }
        match Self::new(config, workspace_dir) {
            Ok(ct) => {
                let arc = Arc::new(ct);
                *guard = Some(Arc::clone(&arc));
                Some(arc)
            }
            Err(e) => {
                tracing::warn!("Failed to (re)initialize global cost tracker: {e}");
                *guard = None;
                None
            }
        }
    }

    pub fn try_get_global() -> Option<Arc<Self>> {
        global_cost_tracker_slot().read().clone()
    }

    pub fn daily_cost_usd(&self) -> f64 {
        self.lock_storage()
            .get_aggregated_costs()
            .map(|(daily, _)| daily)
            .unwrap_or(0.0)
    }
}

fn resolve_storage_path(workspace_dir: &Path) -> Result<PathBuf> {
    let storage_path = workspace_dir.join("state").join("costs.jsonl");
    let legacy_path = workspace_dir.join(".senweavercoding").join("costs.db");

    if !storage_path.exists() && legacy_path.exists() {
        if let Some(parent) = storage_path.parent() {
            fs::create_dir_all(parent)
                .with_context(|| format!("Failed to create directory {}", parent.display()))?;
        }

        if let Err(error) = fs::rename(&legacy_path, &storage_path) {
            tracing::warn!(
                "Failed to move legacy cost storage from {} to {}: {error}; falling back to copy",
                legacy_path.display(),
                storage_path.display()
            );
            fs::copy(&legacy_path, &storage_path).with_context(|| {
                format!(
                    "Failed to copy legacy cost storage from {} to {}",
                    legacy_path.display(),
                    storage_path.display()
                )
            })?;
        }
    }

    Ok(storage_path)
}

fn build_session_model_stats(session_costs: &[CostRecord]) -> HashMap<String, ModelStats> {
    let mut by_model: HashMap<String, ModelStats> = HashMap::new();

    for record in session_costs {
        let entry = by_model
            .entry(record.usage.model.clone())
            .or_insert_with(|| ModelStats {
                model: record.usage.model.clone(),
                cost_usd: 0.0,
                total_tokens: 0,
                request_count: 0,
            });

        entry.cost_usd += record.usage.cost_usd;
        entry.total_tokens += record.usage.total_tokens;
        entry.request_count += 1;
    }

    by_model
}

struct CostStorage {
    path: PathBuf,
    daily_cost_usd: f64,
    monthly_cost_usd: f64,
    cached_day: NaiveDate,
    cached_year: i32,
    cached_month: u32,
}

impl CostStorage {

    fn new(path: &Path) -> Result<Self> {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)
                .with_context(|| format!("Failed to create directory {}", parent.display()))?;
        }

        let now = Utc::now();
        let mut storage = Self {
            path: path.to_path_buf(),
            daily_cost_usd: 0.0,
            monthly_cost_usd: 0.0,
            cached_day: now.date_naive(),
            cached_year: now.year(),
            cached_month: now.month(),
        };

        storage.rebuild_aggregates(
            storage.cached_day,
            storage.cached_year,
            storage.cached_month,
        )?;

        Ok(storage)
    }

    fn for_each_record<F>(&self, mut on_record: F) -> Result<()>
    where
        F: FnMut(CostRecord),
    {
        if !self.path.exists() {
            return Ok(());
        }

        let file = File::open(&self.path)
            .with_context(|| format!("Failed to read cost storage from {}", self.path.display()))?;
        let reader = BufReader::new(file);

        for (line_number, line) in reader.lines().enumerate() {
            let raw_line = line.with_context(|| {
                format!(
                    "Failed to read line {} from cost storage {}",
                    line_number + 1,
                    self.path.display()
                )
            })?;

            let trimmed = raw_line.trim();
            if trimmed.is_empty() {
                continue;
            }

            match serde_json::from_str::<CostRecord>(trimmed) {
                Ok(record) => on_record(record),
                Err(error) => {
                    tracing::warn!(
                        "Skipping malformed cost record at {}:{}: {error}",
                        self.path.display(),
                        line_number + 1
                    );
                }
            }
        }

        Ok(())
    }

    fn rebuild_aggregates(&mut self, day: NaiveDate, year: i32, month: u32) -> Result<()> {
        let mut daily_cost = 0.0;
        let mut monthly_cost = 0.0;

        self.for_each_record(|record| {
            let timestamp = record.usage.timestamp.naive_utc();

            if timestamp.date() == day {
                daily_cost += record.usage.cost_usd;
            }

            if timestamp.year() == year && timestamp.month() == month {
                monthly_cost += record.usage.cost_usd;
            }
        })?;

        self.daily_cost_usd = daily_cost;
        self.monthly_cost_usd = monthly_cost;
        self.cached_day = day;
        self.cached_year = year;
        self.cached_month = month;

        Ok(())
    }

    fn ensure_period_cache_current(&mut self) -> Result<()> {
        let now = Utc::now();
        let day = now.date_naive();
        let year = now.year();
        let month = now.month();

        if day != self.cached_day || year != self.cached_year || month != self.cached_month {
            self.rebuild_aggregates(day, year, month)?;
        }

        Ok(())
    }

    fn add_record(&mut self, record: CostRecord) -> Result<()> {
        let mut file = OpenOptions::new()
            .create(true)
            .append(true)
            .open(&self.path)
            .with_context(|| format!("Failed to open cost storage at {}", self.path.display()))?;

        writeln!(file, "{}", serde_json::to_string(&record)?)
            .with_context(|| format!("Failed to write cost record to {}", self.path.display()))?;

        let day_before = self.cached_day;
        let year_before = self.cached_year;
        let month_before = self.cached_month;
        self.ensure_period_cache_current()?;
        let period_rebuilt = self.cached_day != day_before
            || self.cached_year != year_before
            || self.cached_month != month_before;

        if !period_rebuilt {
            let timestamp = record.usage.timestamp.naive_utc();
            if timestamp.date() == self.cached_day {
                self.daily_cost_usd += record.usage.cost_usd;
            }
            if timestamp.year() == self.cached_year && timestamp.month() == self.cached_month {
                self.monthly_cost_usd += record.usage.cost_usd;
            }
        }

        Ok(())
    }

    fn get_aggregated_costs(&mut self) -> Result<(f64, f64)> {
        self.ensure_period_cache_current()?;
        Ok((self.daily_cost_usd, self.monthly_cost_usd))
    }

    fn get_cost_for_date(&self, date: NaiveDate) -> Result<f64> {
        let mut cost = 0.0;

        self.for_each_record(|record| {
            if record.usage.timestamp.naive_utc().date() == date {
                cost += record.usage.cost_usd;
            }
        })?;

        Ok(cost)
    }

    fn get_cost_for_month(&self, year: i32, month: u32) -> Result<f64> {
        let mut cost = 0.0;

        self.for_each_record(|record| {
            let timestamp = record.usage.timestamp.naive_utc();
            if timestamp.year() == year && timestamp.month() == month {
                cost += record.usage.cost_usd;
            }
        })?;

        Ok(cost)
    }
}
