//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:		
//
//=============================================================================//
#include "cbase.h"
#include "boost/python/detail/wrap_python.hpp"
#include "hl2_pyerrprint.h"
#include "hl2_python.h"
#include "osdefs.h"
#include "frameobject.h"

// disable warning about "assignment within conditional expression"
#pragma warning( disable : 4706 )

// exception printing in python.
static void
print_error_text_hl2(int offset, const char *text)
{
	char *nl;
	if (offset >= 0) {
		if (offset > 0 && offset == (int)strlen(text))
			offset--;
		for (;;) {
			nl = (char *)strchr(text, '\n');
			if (nl == NULL || nl-text >= offset)
				break;
			offset -= (int)(nl+1-text);
			text = nl+1;
		}
		while (*text == ' ' || *text == '\t') {
			text++;
			offset--;
		}
	}
	cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, "    ");
	cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, text);
	if (*text == '\0' || text[strlen(text)-1] != '\n')
		cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, "\n");
	if (offset == -1)
		return;
	cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, "    ");
	offset--;
	while (offset > 0) {
		cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, " ");
		offset--;
	}
	cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, "^\n");
}

static int
parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
		   int *lineno, int *offset, const char **text)
{
	long hold;
	PyObject *v;

	/* old style errors */
	if (PyTuple_Check(err))
		return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
					lineno, offset, text);

	/* new style errors.  `err' is an instance */

	if (! (v = PyObject_GetAttrString(err, "msg")))
		goto finally;
	*message = v;

	if (!(v = PyObject_GetAttrString(err, "filename")))
		goto finally;
	if (v == Py_None)
		*filename = NULL;
	else if (! (*filename = PyString_AsString(v)))
		goto finally;

	Py_DECREF(v);
	if (!(v = PyObject_GetAttrString(err, "lineno")))
		goto finally;
	hold = PyInt_AsLong(v);
	Py_DECREF(v);
	v = NULL;
	if (hold < 0 && PyErr_Occurred())
		goto finally;
	*lineno = (int)hold;

	if (!(v = PyObject_GetAttrString(err, "offset")))
		goto finally;
	if (v == Py_None) {
		*offset = -1;
		Py_DECREF(v);
		v = NULL;
	} else {
		hold = PyInt_AsLong(v);
		Py_DECREF(v);
		v = NULL;
		if (hold < 0 && PyErr_Occurred())
			goto finally;
		*offset = (int)hold;
	}

	if (!(v = PyObject_GetAttrString(err, "text")))
		goto finally;
	if (v == Py_None)
		*text = NULL;
	else if (! (*text = PyString_AsString(v)))
		goto finally;
	Py_DECREF(v);
	return 1;

finally:
	Py_XDECREF(v);
	return 0;
}

static int
tb_displayline(char *filename, int lineno, char *name)
{
	int err = 0;
	FILE *xfp;
	char linebuf[2000];
	int i;
	if (filename == NULL || name == NULL)
		return -1;
	/* This is needed by Emacs' compile command */
#define FMT "  File \"%.500s\", line %d, in %.500s\n"
	//xfp = fopen(filename, "r" PY_STDIOTEXTMODE);
	xfp = NULL;
	if (xfp == NULL) {
		/* Search tail of filename in sys.path before giving up */
		PyObject *path;
		char *tail = strrchr(filename, SEP);
		if (tail == NULL)
			tail = filename;
		else
			tail++;
		path = PySys_GetObject("path");
		if (path != NULL && PyList_Check(path)) {
			Py_ssize_t _npath = PyList_Size(path);
			int npath = Py_SAFE_DOWNCAST(_npath, Py_ssize_t, int);
			size_t taillen = strlen(tail);
			char namebuf[MAXPATHLEN+1];
			for (i = 0; i < npath; i++) {
				PyObject *v = PyList_GetItem(path, i);
				if (v == NULL) {
					PyErr_Clear();
					break;
				}
				if (PyString_Check(v)) {
					size_t len;
					len = PyString_GET_SIZE(v);
					if (len + 1 + taillen >= MAXPATHLEN)
						continue; /* Too long */
					strcpy(namebuf, PyString_AsString(v));
					if (strlen(namebuf) != len)
						continue; /* v contains '\0' */
					if (len > 0 && namebuf[len-1] != SEP)
						namebuf[len++] = SEP;
					strcpy(namebuf+len, tail);
					//xfp = fopen(namebuf, "r" PY_STDIOTEXTMODE);
					xfp = NULL;
					if (xfp != NULL) {
						filename = namebuf;
						break;
					}
				}
			}
		}
	}
	PyOS_snprintf(linebuf, sizeof(linebuf), FMT, filename, lineno, name);
	cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, linebuf);
	if (xfp == NULL)
		return err;
	else if (err != 0) {
		fclose(xfp);
		return err;
	}
	for (i = 0; i < lineno; i++) {
		char* pLastChar = &linebuf[sizeof(linebuf)-2];
		do {
			*pLastChar = '\0';
			//if (Py_UniversalNewlineFgets_HL2(linebuf, sizeof linebuf, xfp, NULL) == NULL)
			//	break;
			/* fgets read *something*; if it didn't get as
			   far as pLastChar, it must have found a newline
			   or hit the end of the file;	if pLastChar is \n,
			   it obviously found a newline; else we haven't
			   yet seen a newline, so must continue */
		} while (*pLastChar != '\0' && *pLastChar != '\n');
	}
	if (i == lineno) {
		char *p = linebuf;
		while (*p == ' ' || *p == '\t' || *p == '\014')
			p++;
		cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, "    ");
		if (err == 0) {
			cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, p);
			if (err == 0 && strchr(p, '\n') == NULL)
				cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, "\n");
		}
	}
	fclose(xfp);
	return err;
}

static int
tb_printinternal(PyTracebackObject *tb, int limit)
{
	int err = 0;
	int depth = 0;
	PyTracebackObject *tb1 = tb;
	while (tb1 != NULL) {
		depth++;
		tb1 = tb1->tb_next;
	}
	while (tb != NULL && err == 0) {
		if (depth <= limit) {
			err = tb_displayline(
			    PyString_AsString(
				    tb->tb_frame->f_code->co_filename),
			    tb->tb_lineno,
			    PyString_AsString(tb->tb_frame->f_code->co_name));
		}
		depth--;
		tb = tb->tb_next;
		if (err == 0)
			err = PyErr_CheckSignals();
	}
	return err;
}

int
PyTraceBack_Print_HL2(PyObject *v)
{
	int err;
	PyObject *limitv;
	int limit = 1000;
	if (v == NULL)
		return 0;
	if (!PyTraceBack_Check(v)) {
		PyErr_BadInternalCall();
		return -1;
	}
	limitv = PySys_GetObject("tracebacklimit");
	if (limitv && PyInt_Check(limitv)) {
		limit = PyInt_AsLong(limitv);
		if (limit <= 0)
			return 0;
	}
	cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, "Traceback (most recent call last):\n");
	//err = PyFile_WriteString("Traceback (most recent call last):\n", f);
	//if (!err)
		err = tb_printinternal((PyTracebackObject *)v, limit);
	return err;
}


void
PyErr_Display_HL2(PyObject *exception, PyObject *value, PyObject *tb)
{
	int err = 0;
	//PyObject *f = PySys_GetObject("stderr");
	Py_INCREF(value);
	//if (f == NULL)
	//	fprintf(stderr, "lost sys.stderr\n");
	//else {
		if (Py_FlushLine())
			PyErr_Clear();
		fflush(stdout);
		if (tb && tb != Py_None)
			err = PyTraceBack_Print_HL2(tb);
		if (err == 0 &&
		    PyObject_HasAttrString(value, "print_file_and_line"))
		{
			PyObject *message;
			const char *filename, *text;
			int lineno, offset;
			if (!parse_syntax_error(value, &message, &filename,
						&lineno, &offset, &text))
				PyErr_Clear();
			else {
				char buf[10];
				cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, "  File \"");
				if (filename == NULL)
					cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, "<string>");
				else
					cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, filename);
				cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, "\", line ");
				PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
				cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, buf);
				cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, "\n");
				if (text != NULL)
					print_error_text_hl2(offset, text);
				Py_DECREF(value);
				value = message;
				/* Can't be bothered to check all those
				   PyFile_WriteString() calls */
				if (PyErr_Occurred())
					err = -1;
			}
		}
		if (err) {
			/* Don't do anything else */
		}
		else if (PyExceptionClass_Check(exception)) {
			PyObject* moduleName;
			char* className = PyExceptionClass_Name(exception);
			if (className != NULL) {
				char *dot = strrchr(className, '.');
				if (dot != NULL)
					className = dot+1;
			}

			moduleName = PyObject_GetAttrString(exception, "__module__");
			if (moduleName == NULL)
				cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, "<unknown>");
			else {
				char* modstr = PyString_AsString(moduleName);
				if (modstr && strcmp(modstr, "exceptions"))
				{
					cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, modstr);
					cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, ".");
				}
				Py_DECREF(moduleName);
			}
			if (err == 0) {
				if (className == NULL)
						cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, "<unknown>");
				else
						cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, className);
			}
		}
		//else
		//	err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
		else
				cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, PyString_AsString(exception));
		if (err == 0 && (value != Py_None)) {
			PyObject *s = PyObject_Str(value);
			/* only print colon if the str() of the
			   object is not the empty string
			*/
			if (s == NULL)
				err = -1;
			else if (!PyString_Check(s) ||
				 PyString_GET_SIZE(s) != 0)
				cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, ": ");
			//if (err == 0)
			//  err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
			if (err == 0)
				cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, PyString_AsString(s));
			Py_XDECREF(s);
		}
		if (err == 0)
			cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, "\n");
	//}
	Py_DECREF(value);
	/* If an error happened here, don't show it.
	   XXX This is wrong, but too many callers rely on this behavior. */
	if (err != 0)
		PyErr_Clear();
}


void
PyErr_PrintEx_HL2(int set_sys_last_vars)
{
	PyObject *exception, *v, *tb, *hook;

	if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
		//handle_system_exit();
		cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, "handle_system_exit\n");
	}
	PyErr_Fetch(&exception, &v, &tb);
		return;

	PyErr_NormalizeException(&exception, &v, &tb);
	if (exception == NULL)
		return;

        /* Now we know v != NULL too */
	if (set_sys_last_vars) {
		PySys_SetObject("last_type", exception);
		PySys_SetObject("last_value", v);
		PySys_SetObject("last_traceback", tb);
	}
	hook = PySys_GetObject("excepthook");
	//hook = sys_excepthook_hl2(Py_None, Py_None );

	if (hook) {
		PyObject *args = PyTuple_Pack(3,
		    exception, v, tb ? tb : Py_None);
		PyObject *result = PyEval_CallObject(hook, args);
		if (result == NULL) {
			PyObject *exception2, *v2, *tb2;
			if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
				//handle_system_exit();
				cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, "handle_system_exit\n");
			}
			PyErr_Fetch(&exception2, &v2, &tb2);
			PyErr_NormalizeException(&exception2, &v2, &tb2);
			/* It should not be possible for exception2 or v2
			   to be NULL. However PyErr_Display() can't
			   tolerate NULLs, so just be safe. */
			if (exception2 == NULL) {
				exception2 = Py_None;
				Py_INCREF(exception2);
			}
			if (v2 == NULL) {
				v2 = Py_None;
				Py_INCREF(v2);
			}
			if (Py_FlushLine())
				PyErr_Clear();
			fflush(stdout);
			cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, "Error in sys.excepthook:\n");
			PyErr_Display_HL2(exception2, v2, tb2);
			cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, "\nOriginal exception was:\n");
			PyErr_Display_HL2(exception, v, tb);
			Py_DECREF(exception2);
			Py_DECREF(v2);
			Py_XDECREF(tb2);
		}
		Py_XDECREF(result);
		Py_XDECREF(args);
	} else {
		cvar->ConsoleColorPrintf( PYTHON_ERROR_PRINT_COLOR, "sys.excepthook is missing\n");
		PyErr_Display_HL2(exception, v, tb);
	}
	Py_XDECREF(exception);
	Py_XDECREF(v);
	Py_XDECREF(tb);
}

void
PyErr_Print_HL2(void)
{
	PyErr_PrintEx_HL2(1);
}