#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
🌐 API RESTful - Sistema Bitcoin Monitor
=========================================

📌 Endpoints disponíveis:

GET  /                      - Página inicial da API
GET  /health                - Health check
GET  /api/report            - Relatório atual
GET  /api/history           - Histórico completo
GET  /api/ai-analysis       - Análise com IA
GET  /api/stats             - Estatísticas gerais
POST /api/trigger-monitor   - Acionar monitoramento manual
POST /api/trigger-ai        - Acionar análise com IA

📌 Como usar:
    python3 bitcoin_api.py

📌 Acesso:
    Local: http://localhost:5000
    Tailscale: http://100.75.88.8:5000

📌 Teste:
    curl http://localhost:5000/health
    curl http://localhost:5000/api/report

🎯 Objetivo: Expor dados via API para integração com outros sistemas

Criado com energia, clareza e propósito.
"""

import json
import subprocess
from datetime import datetime
from pathlib import Path
from flask import Flask, jsonify, request, send_file
from flask_cors import CORS


# ========================================
# 🔧 CONFIGURAÇÃO
# ========================================

app = Flask(__name__)
CORS(app)  # Permite acesso de qualquer origem

# Arquivos
HISTORY_FILE = "bitcoin_history.json"
AI_ANALYSIS_FILE = "bitcoin_ai_analysis.json"
REPORT_FILE = "report.html"

# Porta
PORT = 5001  # Changed from 5000 due to macOS AirPlay Receiver conflict


# ========================================
# 📊 FUNÇÕES AUXILIARES
# ========================================

def load_json_file(filename):
    """
    📂 Carrega arquivo JSON

    Args:
        filename (str): Nome do arquivo

    Returns:
        dict: Dados do arquivo ou None
    """
    if not Path(filename).exists():
        return None

    try:
        with open(filename, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception as e:
        print(f"Erro ao carregar {filename}: {e}")
        return None


def run_script(script_name):
    """
    🚀 Executa script Python

    Args:
        script_name (str): Nome do script

    Returns:
        tuple: (sucesso, saída, erro)
    """
    try:
        result = subprocess.run(
            ['python3', script_name],
            capture_output=True,
            text=True,
            timeout=120
        )

        return (
            result.returncode == 0,
            result.stdout,
            result.stderr
        )
    except subprocess.TimeoutExpired:
        return False, "", "Timeout após 120 segundos"
    except Exception as e:
        return False, "", str(e)


# ========================================
# 🌐 ROTAS DA API
# ========================================

@app.route('/')
def index():
    """
    🏠 Página inicial da API
    """
    return jsonify({
        'name': 'Bitcoin Monitor API',
        'version': '1.0.0',
        'status': 'operational',
        'description': 'API para monitoramento de tendências de Bitcoin',
        'endpoints': {
            'health': '/health',
            'report': '/api/report',
            'history': '/api/history',
            'ai_analysis': '/api/ai-analysis',
            'stats': '/api/stats',
            'trigger_monitor': 'POST /api/trigger-monitor',
            'trigger_ai': 'POST /api/trigger-ai'
        },
        'documentation': 'https://github.com/seu-usuario/bitcoin-monitor',
        'motto': 'O que você não vê, eu vejo.'
    })


@app.route('/health')
def health():
    """
    ❤️ Health check
    """
    # Verifica arquivos
    files_status = {
        'history': Path(HISTORY_FILE).exists(),
        'ai_analysis': Path(AI_ANALYSIS_FILE).exists(),
        'report': Path(REPORT_FILE).exists()
    }

    return jsonify({
        'status': 'healthy',
        'timestamp': datetime.now().isoformat(),
        'version': '1.0.0',
        'files': files_status,
        'uptime': 'N/A'  # Implementar se necessário
    })


@app.route('/api/report')
def get_report():
    """
    📄 Retorna relatório atual
    """
    data = load_json_file(HISTORY_FILE)

    if data is None:
        return jsonify({
            'status': 'error',
            'message': 'Nenhum relatório disponível',
            'suggestion': 'Execute bitcoin_monitor.py primeiro'
        }), 404

    total_volume = sum(data.values()) if isinstance(data, dict) else 0

    return jsonify({
        'status': 'success',
        'timestamp': datetime.now().isoformat(),
        'data': data,
        'summary': {
            'total_keywords': len(data),
            'total_volume': total_volume
        }
    })


@app.route('/api/history')
def get_history():
    """
    📚 Retorna histórico completo
    """
    # Por enquanto, retorna apenas o último relatório
    # TODO: Implementar armazenamento de múltiplos relatórios
    data = load_json_file(HISTORY_FILE)

    if data is None:
        return jsonify({
            'status': 'error',
            'message': 'Nenhum histórico disponível'
        }), 404

    return jsonify({
        'status': 'success',
        'history': [
            {
                'timestamp': datetime.now().isoformat(),
                'data': data
            }
        ],
        'note': 'Histórico completo será implementado em versões futuras'
    })


@app.route('/api/ai-analysis')
def get_ai_analysis():
    """
    🤖 Retorna análise com IA
    """
    analysis = load_json_file(AI_ANALYSIS_FILE)

    if analysis is None:
        return jsonify({
            'status': 'error',
            'message': 'Nenhuma análise disponível',
            'suggestion': 'Execute bitcoin_ai_analyzer.py primeiro'
        }), 404

    return jsonify({
        'status': 'success',
        'analysis': analysis
    })


@app.route('/api/stats')
def get_stats():
    """
    📊 Estatísticas gerais
    """
    data = load_json_file(HISTORY_FILE)
    ai_analysis = load_json_file(AI_ANALYSIS_FILE)

    if data is None:
        return jsonify({
            'status': 'error',
            'message': 'Nenhum dado disponível'
        }), 404

    total_volume = sum(data.values()) if isinstance(data, dict) else 0
    keywords_count = len(data) if isinstance(data, dict) else 0

    # Identifica keyword com maior volume
    max_keyword = None
    max_volume = 0
    if isinstance(data, dict):
        for keyword, volume in data.items():
            if volume > max_volume:
                max_volume = volume
                max_keyword = keyword

    return jsonify({
        'status': 'success',
        'stats': {
            'total_keywords': keywords_count,
            'total_volume': total_volume,
            'highest_volume': {
                'keyword': max_keyword,
                'volume': max_volume
            },
            'has_ai_analysis': ai_analysis is not None,
            'last_update': datetime.now().isoformat()
        }
    })


@app.route('/api/report-html')
def get_report_html():
    """
    📄 Retorna relatório HTML
    """
    if not Path(REPORT_FILE).exists():
        return jsonify({
            'status': 'error',
            'message': 'Relatório HTML não encontrado'
        }), 404

    return send_file(REPORT_FILE, mimetype='text/html')


@app.route('/api/trigger-monitor', methods=['POST'])
def trigger_monitor():
    """
    🚀 Aciona monitoramento manual
    """
    print("📡 Acionando monitoramento manual...")

    success, stdout, stderr = run_script('bitcoin_monitor.py')

    if success:
        return jsonify({
            'status': 'success',
            'message': 'Monitoramento executado com sucesso',
            'output': stdout
        })
    else:
        return jsonify({
            'status': 'error',
            'message': 'Erro ao executar monitoramento',
            'error': stderr
        }), 500


@app.route('/api/trigger-ai', methods=['POST'])
def trigger_ai():
    """
    🤖 Aciona análise com IA
    """
    print("🤖 Acionando análise com IA...")

    success, stdout, stderr = run_script('bitcoin_ai_analyzer.py')

    if success:
        return jsonify({
            'status': 'success',
            'message': 'Análise com IA executada com sucesso',
            'output': stdout
        })
    else:
        return jsonify({
            'status': 'error',
            'message': 'Erro ao executar análise',
            'error': stderr
        }), 500


# ========================================
# ❌ TRATAMENTO DE ERROS
# ========================================

@app.errorhandler(404)
def not_found(error):
    """
    ❌ Erro 404
    """
    return jsonify({
        'status': 'error',
        'code': 404,
        'message': 'Endpoint não encontrado',
        'available_endpoints': [
            '/',
            '/health',
            '/api/report',
            '/api/history',
            '/api/ai-analysis',
            '/api/stats',
            '/api/report-html'
        ]
    }), 404


@app.errorhandler(500)
def internal_error(error):
    """
    ❌ Erro 500
    """
    return jsonify({
        'status': 'error',
        'code': 500,
        'message': 'Erro interno do servidor',
        'details': str(error)
    }), 500


# ========================================
# 🚀 EXECUÇÃO
# ========================================

if __name__ == '__main__':
    print("\n" + "=" * 60)
    print("🌐 API RESTful - Bitcoin Monitor")
    print("=" * 60 + "\n")

    print("📡 Endpoints disponíveis:")
    print(f"   • http://localhost:{PORT}/")
    print(f"   • http://localhost:{PORT}/health")
    print(f"   • http://localhost:{PORT}/api/report")
    print(f"   • http://localhost:{PORT}/api/history")
    print(f"   • http://localhost:{PORT}/api/ai-analysis")
    print(f"   • http://localhost:{PORT}/api/stats")
    print(f"   • http://localhost:{PORT}/api/report-html")
    print(f"   • POST http://localhost:{PORT}/api/trigger-monitor")
    print(f"   • POST http://localhost:{PORT}/api/trigger-ai\n")

    print("🌍 Acesso remoto via Tailscale:")
    print(f"   • http://100.75.88.8:{PORT}/\n")

    print("💡 Teste com:")
    print(f"   curl http://localhost:{PORT}/health")
    print(f"   curl http://localhost:{PORT}/api/report\n")

    print("="  * 60 + "\n")

    app.run(
        host='0.0.0.0',
        port=PORT,
        debug=True
    )