# This file is part of CAT-SOOP
# Copyright (c) 2011-2023 by The CAT-SOOP Developers <catsoop-dev@mit.edu>
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import ast

tutor.qtype_inherit("pythonic")
base, _ = tutor.question("pythonic")

checktext = "Check Formatting"


def handle_check(submissions, **info):
    out = base["handle_check"](submissions, **info)
    if "not properly" in out:
        return out

    sub = submissions[info["csq_name"]]["data"].strip()

    try:
        x = ast.parse(sub).body[0].value
        assert not isinstance(x, ast.BinOp)
        ast.literal_eval(x)
        return out
    except:
        return '<font color="red">Your submission is not a valid Python literal.</font>'


def handle_submission(submissions, **info):
    sub = submissions[info["csq_name"]]["data"].strip()

    inp = info["csq_input_check"](sub)
    if inp is not None:
        return {"score": 0.0, "msg": '<font color="red">%s</font>' % inp}

    try:
        x = ast.parse(sub).body[0].value
        assert not isinstance(x, ast.BinOp)
        ast.literal_eval(x)
    except:
        return {"score": 0.0, "msg": "Value must be a valid Python literal."}

    return base["handle_submission"](submissions, **info)
