from __future__ import annotations

from typing import TYPE_CHECKING

from pydantic import BaseModel, Field

if TYPE_CHECKING:
    from cognite_data_quality._records import RecordsConfig, Violation


class DataModelConfig(BaseModel):
    """Configuration for the target data model."""

    space: str
    external_id: str
    version: str


class CredentialsConfig(BaseModel):
    """Credentials configuration loaded from TOML."""

    project: str
    tenant_id: str
    cdf_cluster: str
    client_id: str
    client_secret: str
    login_flow: str = Field(default="client_credentials")


class RuleConfig(BaseModel):
    """Resolved rule configuration for validation."""

    datamodel: DataModelConfig | None = None
    instance_space: str | None = None
    auto_load_depth: int = Field(default=2)
    verbose: bool = Field(default=True)
    records: RecordsConfig | None = None


class ValidationInput(BaseModel):
    """Input payload for validation handlers (reads instances from CDF via instance_space)."""

    instance_space: str
    shacl_rules: str | None = None
    shacl_rules_file_external_id: str | None = None
    datamodel_space: str | None = None
    datamodel_external_id: str | None = None
    datamodel_version: str | None = None
    verbose: bool = Field(default=True)
    job_run_id: str | None = None
    records_config: RecordsConfig | None = None


class ValidationResult(BaseModel):
    """Result of validation."""

    conforms: bool
    violations: list[Violation] = Field(default_factory=list)
    report_text: str | None = None
    instance_count: int = 0
    records: list[dict] = Field(default_factory=list)
    schema_issues: list[dict] = Field(default_factory=list)  # Schema inconsistencies from data model


# Resolve forward references at runtime
from cognite_data_quality._records import RecordsConfig, Violation  # noqa: E402

RuleConfig.model_rebuild()
ValidationInput.model_rebuild()
ValidationResult.model_rebuild()
