#
#   Imandra Inc.
#
#   speclogician/logic/lib/domain_model.py
#

import asyncio

from speclogician.modeling.domain import BaseStatus
from speclogician.modeling.spec import Spec
from speclogician.logic.api import SpecLogicianImandraX
from speclogician.utils import console

def check_domain_model(spec: Spec, json_only: bool = False) -> None:
    """
    Updates:
    - spec.domain_model.base_has_state
    - spec.domain_model.base_has_action
    - spec.domain_model.base_status  (via ImandraX)
    """
    dm = spec.domain_model

    if not json_only:
        console.print("[bold cyan]Logician[/bold cyan] Checking domain model base")

    # Local checks
    dm.base_has_state = dm.state_specified()
    dm.base_has_action = dm.action_specified()

    if not json_only:
        console.print(
            f"  • has state type : {'✓' if dm.base_has_state else '✗'}\n"
            f"  • has action type: {'✓' if dm.base_has_action else '✗'}"
        )

    # Build "base-only" model and ask ImandraX to load/typecheck it
    base_src = dm.make_iml_model([], [], [])

    async def _check() -> bool:
        async with SpecLogicianImandraX() as ix:
            res = await ix.load_model(base_src)
            return not bool(getattr(res, "has_errors", False))

    try:
        ok = asyncio.run(_check())
    except Exception as e:
        dm.base_status = BaseStatus.UNKNOWN
        if not json_only:
            console.print("[yellow]⚠ Unable to check base model via ImandraX[/yellow]")
            console.print(f"[dim]{e}[/dim]")
        return

    dm.base_status = BaseStatus.VALID if ok else BaseStatus.INVALID_IML

    if not json_only:
        if dm.base_status is BaseStatus.VALID:
            console.print("[green]✓ Base domain model is valid IML[/green]")
        else:
            console.print("[red]✗ Base domain model is invalid IML[/red]")
