"""
Usage Logger - PostgreSQL Implementation
========================================
RULE 7 COMPLIANT: Uses Elestio PostgreSQL via usage_db module.

High-level logger that wraps UsageDatabase for API usage tracking.
"""
import datetime
import logging
from .usage_db import UsageDatabase

logger = logging.getLogger(__name__)


class UsageLogger:
    """
    High-level API usage logger.

    RULE 7 COMPLIANT - Uses PostgreSQL via UsageDatabase.
    """

    def __init__(self):
        """Initialize with Elestio PostgreSQL (no db_path needed)."""
        self.db = UsageDatabase()
        self.db.connect()
        self.db.create_table()

    def log_usage(self, api_name, input_tokens, output_tokens, cost, timestamp=None, metadata=None):
        """Logs API usage details to the PostgreSQL database.

        Args:
            api_name (str): The name of the API being called.
            input_tokens (int): The number of input tokens used.
            output_tokens (int): The number of output tokens used.
            cost (float): The cost of the API call.
            timestamp (datetime.datetime, optional): The timestamp of the API call. Defaults to now.
            metadata (dict, optional): Optional metadata to store with the usage log.
        """
        if timestamp is None:
            timestamp = datetime.datetime.now(datetime.timezone.utc)

        try:
            self.db.insert_usage(api_name, input_tokens, output_tokens, cost, timestamp, metadata)
            logger.info(f"Logged usage for {api_name} at {timestamp} - Cost: {cost}")
        except Exception as e:
            logger.error(f"Failed to log usage for {api_name}: {e}")

    def close(self):
        """Close database connection."""
        self.db.close()


if __name__ == '__main__':
    # Example usage (for testing)
    logging.basicConfig(level=logging.INFO)

    usage_logger = UsageLogger()

    try:
        usage_logger.log_usage(
            api_name='text-davinci-003',
            input_tokens=100,
            output_tokens=50,
            cost=0.01,
            metadata={'model': 'text-davinci-003', 'user_id': 'test_user'}
        )

        usage_logger.log_usage(
            api_name='embedding-ada-002',
            input_tokens=500,
            output_tokens=0,
            cost=0.0005,
            timestamp=datetime.datetime(2024, 1, 1, 12, 0, 0, tzinfo=datetime.timezone.utc)
        )

        logger.info("Example usage logged successfully to PostgreSQL.")
    except Exception as e:
        logger.error(f"Error during example usage: {e}")
    finally:
        usage_logger.close()


# VERIFICATION_STAMP
# Story: GR-010
# Verified By: Claude Opus 4.5
# Verified At: 2026-02-02
# Migration: SQLite -> PostgreSQL (Elestio Core)
# Tests: Pending integration test
