import json
from pathlib import Path
from typing import Any, cast

from core.models import ParsedContract, ParsedInteraction


def read_contract(contract_file: Path) -> ParsedContract:
    _recovered_contract = ParsedContract()

    with open(contract_file) as file:
        json_object = cast(dict[str, Any], json.loads(file.read()))

        _recovered_contract.consumer = json_object["consumer"]["name"]
        _recovered_contract.producer = json_object["provider"]["name"]

        interactions = cast(list[dict[str, Any]], json_object["interactions"])
        for interaction in interactions:
            _recovered_interaction = ParsedInteraction()

            _recovered_interaction.description = interaction["description"]
            _recovered_interaction.matching_rules = interaction["response"][
                "matchingRules"
            ]
            _recovered_interaction.request = interaction["request"]
            _recovered_interaction.response = interaction["response"]

            _recovered_contract.interactions.append(_recovered_interaction)

    return _recovered_contract
