import json
from pathlib import Path
from typing import Any

from pydantic import BaseModel

from core.contract import Contract
from core.schema import generate_matching_rules


def write_contract(
    contract: type[Contract], examples: dict[str, BaseModel], output="./accords"
):
    consumer = contract.consumer
    producer = contract.producer

    interactions = []

    for name, metadata in contract.interactions.items():
        example = examples[name]
        interaction = {
            "description": metadata.path,
            "request": {"method": metadata.http_method, "path": metadata.path},
            "response": {
                "status": 200,
                "body": example.model_dump(),
                "matchingRules": generate_matching_rules(metadata.return_type),
            },
        }
        interactions.append(interaction)

    accord: dict[str, dict[str, str] | list[dict[str, Any]]] = {
        "consumer": {"name": consumer},
        "provider": {"name": producer},
        "interactions": interactions,
    }

    out = Path(output)
    out.mkdir(exist_ok=True)
    with open(out / f"{consumer}-{producer}.json", "w") as f:
        json.dump(accord, f, indent=2)
