from __future__ import annotations

from typing import Any

from pydantic import BaseModel, ConfigDict, Field

from app.modules.rag.code_qa_pipeline.contracts import (
    AnswerSynthesisInput as CodeQaAnswerSynthesisInput,
)
from app.modules.rag.code_qa_pipeline.contracts import (
    DiagnosticsReport as CodeQaDiagnosticsReport,
)
from app.modules.rag.code_qa_pipeline.contracts import (
    EvidenceBundle as CodeQaEvidencePack,
)
from app.modules.rag.code_qa_pipeline.contracts import (
    RetrievalRequest as CodeQaRetrievalRequest,
)
from app.modules.rag.code_qa_pipeline.contracts import (
    RetrievalResult as CodeQaRetrievalResult,
)
from app.modules.rag.intent_router_v2.models import ConversationState, IntentRouterResult, RepoContext


class CodeQaDraftAnswer(BaseModel):
    model_config = ConfigDict(extra="forbid")

    prompt_name: str
    prompt_payload: str
    answer: str = ""


class CodeQaValidationResult(BaseModel):
    model_config = ConfigDict(extra="forbid")

    passed: bool = False
    action: str = "return"
    reasons: list[str] = Field(default_factory=list)


class CodeQaFinalResult(BaseModel):
    model_config = ConfigDict(extra="forbid")

    final_answer: str
    answer_mode: str = "normal"
    repair_used: bool = False
    llm_used: bool = False
    draft_answer: CodeQaDraftAnswer | None = None
    validation: CodeQaValidationResult = Field(default_factory=CodeQaValidationResult)
    router_result: IntentRouterResult | None = None
    retrieval_request: CodeQaRetrievalRequest | None = None
    retrieval_result: CodeQaRetrievalResult | None = None
    evidence_pack: CodeQaEvidencePack | None = None
    diagnostics: CodeQaDiagnosticsReport
    runtime_trace: list[dict[str, Any]] = Field(default_factory=list)


class CodeQaExecutionState(BaseModel):
    model_config = ConfigDict(extra="forbid")

    user_query: str
    rag_session_id: str
    conversation_state: ConversationState = Field(default_factory=ConversationState)
    repo_context: RepoContext = Field(default_factory=RepoContext)
    router_result: IntentRouterResult | None = None
    retrieval_request: CodeQaRetrievalRequest | None = None
    retrieval_result: CodeQaRetrievalResult | None = None
    evidence_pack: CodeQaEvidencePack | None = None
    synthesis_input: CodeQaAnswerSynthesisInput | None = None
    diagnostics: CodeQaDiagnosticsReport | None = None
    answer_mode: str = "normal"
    degraded_message: str = ""
    final_result: CodeQaFinalResult | None = None
