import os, json
import firebase_admin
from firebase_admin import credentials, firestore
from datetime import datetime

_cred_json = os.environ.get("FIREBASE_CREDENTIALS", "")
if _cred_json and not firebase_admin._apps:
    cred = credentials.Certificate(json.loads(_cred_json))
    firebase_admin.initialize_app(cred)

db = firestore.client()
KEYS_COL = "{
  "type": "service_account",
  "project_id": "pyrph-4ddf7",
  "private_key_id": "f1492be6099041e3682b76bf44244c6acdce6d61",
  "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEuwIBADANBgkqhkiG9w0BAQEFAASCBKUwggShAgEAAoIBAQDMb5X7d4DTNoKz\ngjDunsvI6zFbakOX2lEp6mDz1IY9/D/xW/0OnI1jOvw5oqRrND1bjsU6aToMNFRP\npvmw7fqG4Uw+Dk0TE4tJo/LCSB8DRu2dOK8OxoArNd1QzAQrnE3fs3ECNI6ZT+O+\nl/pgnW3CoFYbfoMmN3B4wyR0riUvwuIbLj4T6YQDYMy0pyzSWD1cwuE1W4py+jOE\nbhpFg1zcAtVO8zVSAduVZsPoQ65GFb+46WiQbMFwcRoH9PKnaEE4QlRa1z3zFpCn\nUqNL8IJDXhYf2EBXlw3RQqIKg5ejxxkGlriM1Ym5al8fL4DyKuJKIifcidpJyz0+\nrQtNiU6RAgMBAAECgf8V09Qvr+gRT8Ckv0HPjc+JpD2g2mJdKZzWMjAn2IknanIT\n/b5ce6/yPa9bIq0WGn3H83ZwxiDB138pAgBRjmyGpNzUbgfMrEmIPfkCxVs0/l21\nwQJFPEHIW01F/dfJeubVplMVPodQgeHPImrukIsnkfb0+I0IMjh6rFs4GgqJDr9u\n1PLCXE5aYML0bhKD6dDX4z6UKk3GXHyAhOmjSGRuU84gUovJedtzzrOUOn5A8cYI\nPr6oKRtyAJMvo7AB9hvv3uuXzET31io7g9iaCcHImSRU9e0dX5Rk1xA61eFAMiKC\nJ1TxcFh4cHp2XtWpW6joh4jOd2NTQ2Ws3/3XfYECgYEA9j+c6TQTtOakR4V/6oQL\nbRAx9ud3i1bTIxcoz/98Nz3GmIUFB0q7EKED51CflOoupRI6MaigkQ0ZEwW3YRc4\nRALB/emrXjTkbd7XO4LhfuuHSjnpUhCB+zzmmOJEs1HkDHKdFXAhPGQpKzrp/owJ\nuwYfZTpXsM4n34uA3kFmuAkCgYEA1IgXIIJn7eRg6ReBip+a4jAfs/wBMZ9KFNQ+\nSM2QOwfinHFSB4oxJil6ZXX0l/cGEYEL1wsGl/tLWYmZSfEiaE6qQn0tKb00Auqy\n3VOCSbIryW5WqON+9YovKtgFq1EtfJ3C8EExmRvzohSESedyb7Kg9I91BfipFnht\nvDA1NEkCgYBWCHmY3HH6JQ7GUjUTyVh4nUznl40jqI0R2HiQ2xEZ98JX7TmJh6l9\nsNO9UGTA0WTElW6xhNm8c9gL1lZwXH1y/YerX6VYv6ADZvTJvPttrXpSC5Oh8VSI\nY4mpZnxcLkM/uhd5svhZsiDUErxIC8MmjYgQhOa4Rf6WUpYOkMkDiQKBgDH/2kEB\nrOWghtQPfaBZMBzqaWr0bGt6J/mCfSyvf7EDh+J6Hmw7rJhnxa289FAUA0925owu\nwdxbeDyWTIPCwO99Ij0GKevZ4TSWdoHvNYWU7wwycxzEeIfXfIU90Qeez26zxrqy\n+7Iji0ukPAMO+jMg+RDP9x3yhAUPS/Gr/bhRAoGBAPMXRM0tWYLt7vluO0ct4nwu\ndHxmNlTrJ4UwVuQPM2MUEnWxN4fhIC2F1NJDggD+kcgcxAPZRPN+WqmFaEEqxkcg\nng/WznjQbJ5Rdk44UXCTm5ZREAaVf+VaS1ycsKDuges3rKEb0v8QLXWaxZ69j9+z\nXw8CcLnpAU3P795FS+wl\n-----END PRIVATE KEY-----\n",
  "client_email": "firebase-adminsdk-fbsvc@pyrph-4ddf7.iam.gserviceaccount.com",
  "client_id": "102531300890706291698",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-fbsvc%40pyrph-4ddf7.iam.gserviceaccount.com",
  "universe_domain": "googleapis.com"
}"

def get_key(key_string: str):
    doc = db.collection(KEYS_COL).document(key_string).get()
    return doc.to_dict() if doc.exists else None

def save_key(data: dict):
    db.collection(KEYS_COL).document(data["key_string"]).set(data)

def update_key(key_string: str, updates: dict):
    db.collection(KEYS_COL).document(key_string).update(updates)

def list_keys(limit=300):
    docs = db.collection(KEYS_COL).order_by(
        "created_at", direction=firestore.Query.DESCENDING
    ).limit(limit).stream()
    return [d.to_dict() for d in docs]

def init_db():
    pass
