"""
Resolves effective API credentials by layering the Settings page (DB-stored,
editable from the UI) over the static .env config — DB values win when present.
Lets the app be configured entirely through the UI instead of editing files.
"""
import json
import os
from extensions import db
from models import AppSettings


def get_settings():
    """Returns the singleton AppSettings row, creating an empty one if needed."""
    settings = AppSettings.query.first()
    if not settings:
        settings = AppSettings()
        db.session.add(settings)
        db.session.commit()
    return settings


def get_effective_config(app_config):
    """Merges DB settings over app.config. Returns a plain dict with:
    GOOGLE_CREDENTIALS_SOURCE (dict parsed from JSON, a file path string, or None),
    PAGESPEED_API_KEY, ANTHROPIC_API_KEY, CLAUDE_MODEL."""
    settings = get_settings()

    credentials_source = None
    if settings.google_service_account_json:
        try:
            credentials_source = json.loads(settings.google_service_account_json)
        except ValueError:
            credentials_source = None
    if credentials_source is None:
        file_path = app_config.get('GOOGLE_SERVICE_ACCOUNT_FILE')
        if file_path and os.path.exists(file_path):
            credentials_source = file_path

    return {
        'GOOGLE_CREDENTIALS_SOURCE': credentials_source,
        'PAGESPEED_API_KEY': settings.pagespeed_api_key or app_config.get('PAGESPEED_API_KEY') or '',
        'ANTHROPIC_API_KEY': settings.anthropic_api_key or app_config.get('ANTHROPIC_API_KEY') or '',
        'CLAUDE_MODEL': settings.claude_model or app_config.get('CLAUDE_MODEL') or 'claude-sonnet-5',
    }
