"""
billing.py — Fungsi-fungsi untuk manajemen saldo dan tarif.
"""

import subprocess
import math
from sqlalchemy.orm import Session
from app.models.service_rate import ServiceRate
from app.models.user import User
from app.models.transaksi import Transaction

def get_audio_duration(file_path: str) -> float:
    """Mendapatkan durasi audio dalam detik menggunakan ffprobe."""
    try:
        cmd = [
            "ffprobe", "-v", "error", "-show_entries", "format=duration",
            "-of", "default=noprint_wrappers=1:nokey=1", file_path
        ]
        output = subprocess.check_output(cmd, text=True).strip()
        return float(output)
    except Exception as e:
        raise ValueError(f"Tidak dapat membaca durasi audio: {e}")

def get_transcription_rate(db: Session) -> int:
    rate = db.query(ServiceRate).filter(ServiceRate.key == "transcription_rate_per_minute").first()
    return rate.value if rate else 5000

def get_ba_rate(db: Session) -> int:
    rate = db.query(ServiceRate).filter(ServiceRate.key == "ba_rate").first()
    return rate.value if rate else 20000

def calculate_transcription_cost(duration_seconds: float, rate_per_minute: int) -> int:
    minutes_rounded = math.ceil(duration_seconds / 60.0)
    return minutes_rounded * rate_per_minute

def deduct_balance(db: Session, user_id: int, amount: int, service_type: str,
                   task_id=None, ba_id=None, description=None) -> int:
    """Potong saldo user, amount positif, simpan transaksi negatif."""
    user = db.query(User).filter(User.id == user_id).with_for_update().first()
    if user.balance < amount:
        raise ValueError(f"Saldo tidak mencukupi. Saldo Anda: Rp {user.balance:,}, diperlukan: Rp {amount:,}")
    user.balance -= amount
    trans = Transaction(
        user_id=user_id,
        amount=-amount,
        service_type=service_type,
        task_id=task_id,
        ba_id=ba_id,
        description=description
    )
    db.add(trans)
    db.commit()
    return user.balance

def add_balance(db: Session, user_id: int, amount: int, description=None) -> int:
    """Tambah saldo user, amount positif."""
    user = db.query(User).filter(User.id == user_id).with_for_update().first()
    user.balance += amount
    trans = Transaction(
        user_id=user_id,
        amount=amount,
        service_type="topup",
        description=description
    )
    db.add(trans)
    db.commit()
    return user.balance

def refund_balance(db: Session, user_id: int, amount: int, service_type: str,
                   task_id=None, ba_id=None, description=None) -> int:
    """Refund (tambah saldo kembali) karena proses gagal."""
    user = db.query(User).filter(User.id == user_id).with_for_update().first()
    user.balance += amount
    trans = Transaction(
        user_id=user_id,
        amount=amount,
        service_type=service_type,
        task_id=task_id,
        ba_id=ba_id,
        description=f"Refund: {description}" if description else "Refund"
    )
    db.add(trans)
    db.commit()
    return user.balance