import os
import sys
from pathlib import Path

# Asegurar que el proyecto está en el sys.path
PROJECT_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT_ROOT))

from app import create_app
from app.blueprints.admin.blog_routes import _generate_featured_image, _download_and_save_image


def main():
    app = create_app('development')
    with app.app_context():
        print('UPLOAD_FOLDER:', app.config['UPLOAD_FOLDER'], flush=True)
        print('FREEPIK_API_KEY present:', bool(os.getenv('FREEPIK_API_KEY')), flush=True)

        title = 'Prueba energía solar en España'
        content = 'Paneles solares fotovoltaicos y autoconsumo residencial'

        # 1) Intentar generar imagen con Freepik
        path = _generate_featured_image(title, content)
        print('FEATURED_IMAGE_PATH:', path, flush=True)

        client = app.test_client()
        status = client.get(f'/uploads/{path}').status_code if path else None
        print('UPLOADS_GET_STATUS:', status, flush=True)

        # 2) Si falla Freepik, probar flujo con URL pública conocida (placeholder)
        if not path or status != 200:
            print('Falling back to placeholder download...', flush=True)
            fallback_url = 'https://placehold.co/1792x1024.jpg'
            fallback_path = _download_and_save_image(fallback_url, 'prueba_fallback')
            print('FALLBACK_PATH:', fallback_path, flush=True)
            status2 = client.get(f'/uploads/{fallback_path}').status_code if fallback_path else None
            print('FALLBACK_GET_STATUS:', status2, flush=True)


if __name__ == '__main__':
    main()
