import json
import urllib.parse
import urllib.request
from flask import Blueprint, render_template, redirect, url_for, current_app, request, Response

from app.blueprints.access_controls import ac_requires, ac_api_requires
from app.models.authorization import Permissions

kpi_dashboard_blueprint = Blueprint(
    'kpi_dashboard', __name__, template_folder='templates'
)


def _soc_url() -> str:
    return current_app.config.get('SOC_INTEGRATOR_URL', 'http://soc-integrator:8000')


def _soc_get(path: str, params: dict) -> tuple[bytes, int, str]:
    qs = urllib.parse.urlencode({k: v for k, v in params.items() if v is not None})
    url = f"{_soc_url()}{path}{'?' + qs if qs else ''}"
    with urllib.request.urlopen(url, timeout=30) as r:
        return r.read(), r.status, r.headers.get('Content-Type', 'application/json')


def _soc_post(path: str, body: dict) -> tuple[bytes, int]:
    url = f"{_soc_url()}{path}"
    data = json.dumps(body).encode()
    req = urllib.request.Request(url, data=data, headers={'Content-Type': 'application/json'})
    with urllib.request.urlopen(req, timeout=20) as r:
        return r.read(), r.status


@kpi_dashboard_blueprint.route('/kpi-dashboard')
@ac_requires(no_cid_required=True)
def kpi_dashboard(caseid, url_redir):
    if url_redir:
        return redirect(url_for('index.index', cid=caseid if caseid is not None else 1, redirect=True))
    return render_template('kpi_dashboard.html')


@kpi_dashboard_blueprint.route('/kpi-dashboard/api/alerts')
@ac_api_requires(Permissions.alerts_read)
def proxy_list_alerts():
    content, status, _ = _soc_get('/iris/alerts', request.args)
    return Response(content, status=status, content_type='application/json')


@kpi_dashboard_blueprint.route('/kpi-dashboard/api/alerts/<int:alert_id>')
@ac_api_requires(Permissions.alerts_read)
def proxy_get_alert(alert_id):
    content, status, _ = _soc_get(f'/iris/alerts/{alert_id}', {})
    return Response(content, status=status, content_type='application/json')


@kpi_dashboard_blueprint.route('/kpi-dashboard/api/alerts/<int:alert_id>/assign', methods=['POST'])
@ac_api_requires(Permissions.alerts_write)
def proxy_assign_alert(alert_id):
    content, status = _soc_post(f'/iris/alerts/{alert_id}/assign', request.get_json() or {})
    return Response(content, status=status, content_type='application/json')


@kpi_dashboard_blueprint.route('/kpi-dashboard/api/alerts/export-csv')
@ac_api_requires(Permissions.alerts_read)
def proxy_export_csv():
    content, status, _ = _soc_get('/iris/alerts/export-csv', request.args)
    return Response(
        content,
        status=status,
        content_type='text/csv',
        headers={'Content-Disposition': 'attachment; filename=iris_alerts.csv'},
    )


@kpi_dashboard_blueprint.route('/kpi-dashboard/api/cases')
@ac_api_requires(Permissions.alerts_read)
def proxy_list_cases():
    content, status, _ = _soc_get('/iris/cases', request.args)
    return Response(content, status=status, content_type='application/json')


@kpi_dashboard_blueprint.route('/kpi-dashboard/api/cases/<int:case_id>')
@ac_api_requires(Permissions.alerts_read)
def proxy_get_case(case_id):
    content, status, _ = _soc_get(f'/iris/cases/{case_id}', {})
    return Response(content, status=status, content_type='application/json')
