import os
import re
import json
from typing import Optional, Any

from dotenv import load_dotenv
from google import genai

from database import get_connection


# =========================================================
# ENV
# =========================================================

load_dotenv()

GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")

if not GEMINI_API_KEY:
    raise RuntimeError("GEMINI_API_KEY is missing in .env file")

MODEL_NAME = os.getenv(
    "GEMINI_MODEL",
    "gemini-3.6-flash"
)


# =========================================================
# GEMINI CLIENT
# =========================================================

client = genai.Client(
    api_key=GEMINI_API_KEY
)


# =========================================================
# PUBLIC CONTENT TABLES
#
# IMPORTANT:
# These are ONLY public portal/content tables.
#
# User/private tables such as:
# users, wallet, documents, family, applications
# are NOT globally searched.
# =========================================================

PUBLIC_TABLE_HINTS = {
    "jobs",
    "job",
    "job_editor",
    "job_batches",

    "forms",
    "government_forms",
    "csc_forms",
    "csc_documents",
    "csc_documents_editor",
    "documents",

    "admissions",
    "admission",

    "admit_cards",
    "admit_card",
    "admit_cards_editor",

    "govt_schemes",
    "government_schemes",
    "schemes",

    "entrance_exams",
    "entrance_exam",
    "entrance_exam_dates",
    "exams",
    "exam",

    "exam_results",
    "exam_result",
    "results",
    "result",

    "scholarships",
    "scholarship",
    "scholarship_editor",

    "important_updates",
    "important_update",

    "csc_updates",
    "csc_update",

    "business_services",
    "services",
    "csc_services",
    "chatbot_services",

    "editor",
}


# =========================================================
# PRIVATE / USER TABLES
# NEVER GLOBAL SEARCH THESE
# =========================================================

PRIVATE_TABLES = {
    "users",
    "csc_users",
    "user",
    "wallet",
    "wallet_transactions",
    "csc_wallet",
    "documents_private",
    "family",
    "families",
    "family_members",
    "applications",
    "csc_applications",
    "job_applications",
}


# =========================================================
# TEXT NORMALIZATION
# =========================================================

def normalize_text(text: str) -> str:

    message = str(text or "").lower().strip()

    replacements = {
        "staus": "status",
        "stauts": "status",
        "statuz": "status",

        "aplication": "application",
        "applcation": "application",
        "applicaton": "application",

        "reslt": "result",
        "resultt": "result",

        "admitcard": "admit card",

        "govt": "government",
        "gov": "government",

        "scholar ship": "scholarship",

        "chaiye": "chahiye",
        "bnana": "banana",
        "bnwane": "banwane",
        "krna": "karna",
        "kru": "karu",
        "kaisee": "kaise",

        "htetform": "htet form",
        "ctetform": "ctet form",
    }

    for wrong, correct in replacements.items():
        message = message.replace(wrong, correct)

    message = re.sub(r"\s+", " ", message)

    return message


# =========================================================
# INTENT DETECTION
# =========================================================

def detect_intent(text: str):

    message = normalize_text(text)

    # -----------------------------------------------------
    # Application
    # -----------------------------------------------------

    application_keywords = [
        "application status",
        "application ka status",
        "meri application",
        "mera application",
        "meri application ka",
        "my application",
        "my applications",
        "application track",
        "track application",
        "application tracking",
        "form status",
        "status of application",
        "application ki status",
        "application kaha",
        "application kahan",
    ]

    if any(x in message for x in application_keywords):
        return "application", 0.98


    # -----------------------------------------------------
    # Jobs
    # -----------------------------------------------------

    job_keywords = [
        "government job",
        "government jobs",
        "government job chahiye",
        "government jobs chahiye",
        "latest government job",
        "latest government jobs",
        "latest jobs",
        "sarkari job",
        "sarkari jobs",
        "sarkari naukri",
        "sarkari naukri chahiye",
        "government vacancy",
        "government vacancies",
        "sarkari vacancy",
        "vacancy",
        "vacancies",
        "recruitment",
        "job notification",
        "job notifications",
    ]

    if any(x in message for x in job_keywords):
        return "jobs", 0.98


    # -----------------------------------------------------
    # SPECIFIC EXAM / ENTITY
    #
    # IMPORTANT:
    # This MUST come before generic forms.
    # -----------------------------------------------------

    specific_exam_keywords = [
        "htet",
        "htet form",
        "htet exam",
        "htet registration",
        "htet application",

        "ctet",
        "ctet form",
        "ctet exam",

        "neet",
        "neet form",
        "neet exam",

        "jee",
        "jee form",
        "jee exam",

        "cuet",
        "cuet form",
        "cuet exam",
    ]

    if any(x in message for x in specific_exam_keywords):
        return "exam", 0.99


    # -----------------------------------------------------
    # Forms
    # -----------------------------------------------------

    form_keywords = [
        "government form",
        "government forms",
        "government form chahiye",
        "government forms chahiye",
        "sarkari form",
        "sarkari forms",
        "sarkari form chahiye",
        "govt form",
        "govt forms",
        "form chahiye",
        "forms chahiye",
        "form dikhao",
        "forms dikhao",
        "government forms dikhao",
        "online form",
        "online forms",
    ]

    if any(x in message for x in form_keywords):
        return "forms", 0.98


    # -----------------------------------------------------
    # PAN
    # -----------------------------------------------------

    pan_keywords = [
        "pan card",
        "pancard",
        "pan form",
        "pan card form",
        "pan card kaise",
        "how to apply pan",
        "apply pan",
    ]

    if any(x in message for x in pan_keywords):
        return "forms", 0.95


    # -----------------------------------------------------
    # Scholarship
    # -----------------------------------------------------

    scholarship_keywords = [
        "scholarship",
        "scholarships",
        "scholarship form",
        "scholarship forms",
        "scholarship chahiye",
        "scholarship ke liye",
    ]

    if any(x in message for x in scholarship_keywords):
        return "scholarship", 0.98


    # -----------------------------------------------------
    # Admit Card
    # -----------------------------------------------------

    admit_keywords = [
        "admit card",
        "admit cards",
        "hall ticket",
        "admit card kab",
        "admit card download",
        "admit card chahiye",
    ]

    if any(x in message for x in admit_keywords):
        return "admit", 0.98


    # -----------------------------------------------------
    # Results
    # -----------------------------------------------------

    result_keywords = [
        "result",
        "results",
        "exam result",
        "exam results",
        "mera result",
        "result check",
        "result kaise dekhu",
        "result chahiye",
    ]

    if any(x in message for x in result_keywords):
        return "result", 0.98


    # -----------------------------------------------------
    # Exam
    # -----------------------------------------------------

    exam_keywords = [
        "exam date",
        "exam ki date",
        "exam kab",
        "exam schedule",
        "paper kab hai",
        "exam dates",
    ]

    if any(x in message for x in exam_keywords):
        return "exam", 0.95


    # -----------------------------------------------------
    # Government Scheme
    # -----------------------------------------------------

    scheme_keywords = [
        "government scheme",
        "government schemes",
        "govt scheme",
        "govt schemes",
        "sarkari yojana",
        "sarkari yojna",
        "government yojana",
        "scheme",
        "schemes",
        "yojana",
        "yojna",
    ]

    if any(x in message for x in scheme_keywords):
        return "scheme", 0.98


    # -----------------------------------------------------
    # Services
    # -----------------------------------------------------

    service_keywords = [
        "csc service",
        "csc services",
        "csc service dikhao",
        "csc services dikhao",
        "service",
        "services",
        "service dikhao",
        "services dikhao",
        "csc seva",
        "seva",
        "csc seva dikhao",
    ]

    if any(x in message for x in service_keywords):
        return "services", 0.98


    # -----------------------------------------------------
    # Updates
    # -----------------------------------------------------

    update_keywords = [
        "latest update",
        "latest updates",
        "csc update",
        "csc updates",
        "latest news",
        "important update",
        "important updates",
    ]

    if any(x in message for x in update_keywords):
        return "updates", 0.95


    # -----------------------------------------------------
    # Profile
    # -----------------------------------------------------

    profile_keywords = [
        "profile",
        "my profile",
        "account details",
        "profile update",
        "meri profile",
    ]

    if any(x in message for x in profile_keywords):
        return "profile", 0.95


    # -----------------------------------------------------
    # Greeting
    # -----------------------------------------------------

    if re.search(
        r"\b(hi|hii|hello|hey|namaste|namaskar)\b",
        message,
    ):
        return "greeting", 0.99


    return "general", 0.50


# =========================================================
# DB HELPERS
# =========================================================

def get_cursor(conn):

    try:
        return conn.cursor(dictionary=True)

    except TypeError:

        return conn.cursor()


def rows_to_dicts(cursor, rows):

    if not rows:
        return []

    if isinstance(rows[0], dict):
        return rows

    columns = []

    try:
        columns = [
            col[0]
            for col in cursor.description
        ]

    except Exception:
        pass

    result = []

    for row in rows:

        try:
            result.append(
                dict(zip(columns, row))
            )

        except Exception:
            pass

    return result


# =========================================================
# TABLE EXISTS
# =========================================================

def table_exists(conn, table_name: str) -> bool:

    cursor = get_cursor(conn)

    try:

        cursor.execute(
            """
            SELECT COUNT(*) AS total
            FROM information_schema.tables
            WHERE table_schema = DATABASE()
            AND table_name = %s
            """,
            (table_name,)
        )

        row = cursor.fetchone()

        if isinstance(row, dict):
            return int(
                row.get("total", 0)
            ) > 0

        return bool(
            row and row[0]
        )

    except Exception as e:

        print(
            f"TABLE CHECK ERROR [{table_name}]:",
            str(e)
        )

        return False

    finally:

        cursor.close()


# =========================================================
# GET TABLE COLUMNS
# =========================================================

def get_table_columns(conn, table_name: str):

    cursor = get_cursor(conn)

    try:

        cursor.execute(
            """
            SELECT COLUMN_NAME
            FROM information_schema.columns
            WHERE table_schema = DATABASE()
            AND table_name = %s
            ORDER BY ORDINAL_POSITION
            """,
            (table_name,)
        )

        rows = cursor.fetchall()

        data = rows_to_dicts(
            cursor,
            rows
        )

        return [
            str(
                row.get("COLUMN_NAME")
            )
            for row in data
            if row.get("COLUMN_NAME")
        ]

    except Exception as e:

        print(
            f"COLUMN ERROR [{table_name}]:",
            str(e)
        )

        return []

    finally:

        cursor.close()


# =========================================================
# GET ALL PUBLIC TABLES AUTOMATICALLY
#
# This is the important part.
#
# We don't depend ONLY on hard-coded candidates.
# Database itself tells us what tables exist.
# =========================================================

def get_public_tables(conn):

    cursor = get_cursor(conn)

    try:

        cursor.execute(
            """
            SELECT table_name
            FROM information_schema.tables
            WHERE table_schema = DATABASE()
            AND table_type = 'BASE TABLE'
            """
        )

        rows = cursor.fetchall()

        data = rows_to_dicts(
            cursor,
            rows
        )

        tables = []

        for row in data:

            name = (
                row.get("TABLE_NAME")
                or row.get("table_name")
            )

            if not name:
                continue

            name = str(name)

            lower_name = name.lower()

            if lower_name in PRIVATE_TABLES:
                continue

            # Explicit public content tables
            if lower_name in PUBLIC_TABLE_HINTS:
                tables.append(name)
                continue

            # Automatically recognize content-like tables
            content_words = [
                "job",
                "form",
                "exam",
                "result",
                "admit",
                "scholar",
                "scheme",
                "service",
                "update",
                "admission",
                "editor",
            ]

            if any(
                word in lower_name
                for word in content_words
            ):
                tables.append(name)

        # Remove duplicates
        return list(
            dict.fromkeys(tables)
        )

    except Exception as e:

        print(
            "PUBLIC TABLE DISCOVERY ERROR:",
            str(e)
        )

        return []

    finally:

        cursor.close()


# =========================================================
# GET TABLE ROWS
# =========================================================

def get_table_rows(
    conn,
    table_name: str,
    limit: int = 10
):

    if not table_exists(
        conn,
        table_name
    ):
        return []

    cursor = get_cursor(conn)

    try:

        columns = get_table_columns(
            conn,
            table_name
        )

        order_column = None

        for candidate in [
            "id",
            "created_at",
            "updated_at",
            "job_id",
            "service_id",
            "exam_id",
            "result_id",
            "admit_card_id",
            "scholarship_id",
            "scheme_id",
        ]:

            if candidate in columns:

                order_column = candidate
                break

        if order_column:

            query = f"""
                SELECT *
                FROM `{table_name}`
                ORDER BY `{order_column}` DESC
                LIMIT %s
            """

        else:

            query = f"""
                SELECT *
                FROM `{table_name}`
                LIMIT %s
            """

        cursor.execute(
            query,
            (limit,)
        )

        rows = cursor.fetchall()

        return rows_to_dicts(
            cursor,
            rows
        )

    except Exception as e:

        print(
            f"DB READ ERROR [{table_name}]:",
            str(e)
        )

        return []

    finally:

        cursor.close()


# =========================================================
# EXTRACT SEARCH TERMS
# =========================================================

def extract_search_terms(message: str):

    message = normalize_text(
        message
    )

    words = re.findall(
        r"[a-zA-Z0-9\u0900-\u097F]+",
        message.lower()
    )

    ignored_words = {
        "latest",
        "government",
        "govt",
        "sarkari",
        "job",
        "jobs",
        "form",
        "forms",
        "chahiye",
        "dikhao",
        "show",
        "me",
        "mujhe",
        "please",
        "csc",
        "service",
        "services",
        "seva",
        "ka",
        "ki",
        "ke",
        "ko",
        "hai",
        "hain",
        "kya",
        "kaise",
        "kahan",
        "kaha",
        "for",
        "the",
        "and",
        "my",
        "mera",
        "meri",
        "application",
        "status",
    }

    words = [
        word
        for word in words
        if len(word) >= 2
        and word not in ignored_words
    ]

    # Preserve order and remove duplicates
    words = list(
        dict.fromkeys(words)
    )

    return words[:8]


# =========================================================
# SEARCH ONE TABLE
# =========================================================

def search_table(
    conn,
    table_name: str,
    message: str,
    limit: int = 10
):

    if not table_exists(
        conn,
        table_name
    ):
        return []

    columns = get_table_columns(
        conn,
        table_name
    )

    if not columns:
        return []

    # -----------------------------------------------------
    # Searchable columns
    # -----------------------------------------------------

    preferred = [
        "title",
        "name",

        "job_title",
        "post_name",
        "post",

        "service_name",

        "form_name",
        "document_name",

        "scheme_name",

        "scholarship_name",

        "exam_name",
        "exam_title",

        "result_name",

        "admit_card_name",

        "update_title",
        "heading",

        "description",
        "short_description",

        "category",
        "department",
        "organization",
        "company",

        "qualification",
        "eligibility",

        "course_name",

        "notification_name",
    ]

    searchable_columns = [
        column
        for column in preferred
        if column in columns
    ]

    # -----------------------------------------------------
    # If preferred columns unavailable,
    # automatically use text-like columns
    # -----------------------------------------------------

    if not searchable_columns:

        excluded = {
            "id",
            "created_at",
            "updated_at",
            "deleted_at",
        }

        searchable_columns = [
            column
            for column in columns
            if column not in excluded
        ][:12]

    terms = extract_search_terms(
        message
    )

    cursor = get_cursor(conn)

    try:

        # -------------------------------------------------
        # No useful search term
        # -------------------------------------------------

        if not terms:

            return get_table_rows(
                conn,
                table_name,
                limit
            )

        # -------------------------------------------------
        # IMPORTANT:
        #
        # We use OR between terms.
        #
        # So:
        # "htet form"
        #
        # searches:
        # htet
        #
        # and does NOT require every word.
        # -------------------------------------------------

        conditions = []
        params = []

        for term in terms:

            word_conditions = []

            for column in searchable_columns:

                word_conditions.append(
                    f"""
                    LOWER(
                        CAST(`{column}` AS CHAR)
                    ) LIKE %s
                    """
                )

                params.append(
                    f"%{term}%"
                )

            if word_conditions:

                conditions.append(
                    "("
                    + " OR ".join(
                        word_conditions
                    )
                    + ")"
                )

        if not conditions:

            return []

        query = f"""
            SELECT *
            FROM `{table_name}`
            WHERE
            {" OR ".join(conditions)}
            LIMIT %s
        """

        params.append(limit)

        cursor.execute(
            query,
            tuple(params)
        )

        rows = cursor.fetchall()

        return rows_to_dicts(
            cursor,
            rows
        )

    except Exception as e:

        print(
            f"SEARCH ERROR [{table_name}]:",
            str(e)
        )

        return []

    finally:

        cursor.close()


# =========================================================
# AUTOMATIC DATABASE SEARCH
#
# This is the NEW CORE.
# =========================================================

def search_database_automatically(
    conn,
    message: str,
    intent: str,
    limit_per_table: int = 10,
):

    print(
        "================================="
    )

    print(
        "AUTOMATIC DATABASE SEARCH"
    )

    print(
        "SEARCH MESSAGE:",
        message
    )

    print(
        "INTENT:",
        intent
    )

    # -----------------------------------------------------
    # Application is special:
    # NEVER globally search applications.
    # -----------------------------------------------------

    if intent == "application":

        return []

    # -----------------------------------------------------
    # Profile is special.
    # -----------------------------------------------------

    if intent == "profile":

        return []

    # -----------------------------------------------------
    # Greeting doesn't need DB.
    # -----------------------------------------------------

    if intent == "greeting":

        return []

    # -----------------------------------------------------
    # Discover tables automatically
    # -----------------------------------------------------

    tables = get_public_tables(
        conn
    )

    print(
        "PUBLIC TABLES DISCOVERED:",
        tables
    )

    if not tables:

        print(
            "NO PUBLIC TABLES FOUND"
        )

        return []

    all_rows = []

    # -----------------------------------------------------
    # Search every public content table
    # -----------------------------------------------------

    for table in tables:

        rows = search_table(
            conn,
            table,
            message,
            limit_per_table
        )

        if rows:

            print(
                f"DB MATCH: {table} = {len(rows)}"
            )

            for row in rows:

                all_rows.append(
                    {
                        "_source_table": table,
                        **row
                    }
                )

    print(
        "TOTAL AUTOMATIC DB MATCHES:",
        len(all_rows)
    )

    print(
        "================================="
    )

    return rank_database_results(
        all_rows,
        message
    )


# =========================================================
# RANK DATABASE RESULTS
#
# Exact phrase / exact term matches first.
# =========================================================

def rank_database_results(
    rows,
    message: str
):

    if not rows:
        return []

    message_normalized = normalize_text(
        message
    )

    terms = extract_search_terms(
        message_normalized
    )

    def score(row):

        text_parts = []

        for key, value in row.items():

            if str(key).startswith("_"):
                continue

            if value is None:
                continue

            text_parts.append(
                str(value).lower()
            )

        searchable_text = " ".join(
            text_parts
        )

        score_value = 0

        # Exact full query
        if message_normalized in searchable_text:
            score_value += 100

        # Individual terms
        for term in terms:

            if term in searchable_text:
                score_value += 20

        # Source/category relevance
        source = str(
            row.get(
                "_source_table",
                ""
            )
        ).lower()

        if "exam" in source:
            if any(
                term in {
                    "htet",
                    "ctet",
                    "neet",
                    "jee",
                    "cuet",
                }
                for term in terms
            ):
                score_value += 30

        return score_value

    ranked = sorted(
        rows,
        key=score,
        reverse=True
    )

    return ranked[:30]


# =========================================================
# CATEGORY FALLBACK SEARCH
#
# If automatic search gives nothing, category-specific
# search still gets a chance.
# =========================================================

def get_database_data(
    intent: str,
    message: str,
    user_id: Optional[str] = None,
):

    conn = None

    try:

        conn = get_connection()

        print(
            "CHATBOT DB INTENT:",
            intent
        )

        # =================================================
        # APPLICATION
        # =================================================

        if intent == "application":

            if not user_id:

                print(
                    "APPLICATION STATUS: user_id missing"
                )

                return []

            candidates = [
                "csc_applications",
                "job_applications",
                "applications",
            ]

            all_rows = []

            for table in candidates:

                if not table_exists(
                    conn,
                    table
                ):
                    continue

                columns = get_table_columns(
                    conn,
                    table
                )

                user_columns = [
                    "user_id",
                    "userId",
                    "userid",
                    "csc_user_id",
                    "employee_id",
                    "customer_id",
                ]

                matching_column = next(
                    (
                        col
                        for col in user_columns
                        if col in columns
                    ),
                    None
                )

                if not matching_column:
                    continue

                cursor = get_cursor(conn)

                try:

                    query = f"""
                        SELECT *
                        FROM `{table}`
                        WHERE `{matching_column}` = %s
                        ORDER BY id DESC
                        LIMIT 20
                    """

                    cursor.execute(
                        query,
                        (user_id,)
                    )

                    rows = cursor.fetchall()

                    data = rows_to_dicts(
                        cursor,
                        rows
                    )

                    if data:

                        all_rows.extend(
                            [
                                {
                                    "_source_table": table,
                                    **row
                                }
                                for row in data
                            ]
                        )

                except Exception as e:

                    print(
                        f"APPLICATION DB ERROR [{table}]:",
                        str(e)
                    )

                finally:

                    cursor.close()

            return all_rows[:20]

        # =================================================
        # EVERYTHING ELSE:
        # AUTOMATIC DATABASE SEARCH
        # =================================================

        return search_database_automatically(
            conn=conn,
            message=message,
            intent=intent,
            limit_per_table=10,
        )

    except Exception as e:

        print(
            "CHATBOT DATABASE ERROR:",
            str(e)
        )

        return []

    finally:

        if conn:

            try:
                conn.close()

            except Exception:
                pass


# =========================================================
# CLEAN DATABASE DATA
# =========================================================

def clean_database_data(rows):

    cleaned = []

    for row in rows:

        item = {}

        for key, value in row.items():

            if key.startswith("_"):
                continue

            if value is None:
                continue

            try:

                json.dumps(
                    value
                )

                item[key] = value

            except Exception:

                item[key] = str(
                    value
                )

        if item:

            cleaned.append(item)

    return cleaned


# =========================================================
# FIRST VALUE
# =========================================================

def first_value(row, names):

    for name in names:

        value = row.get(name)

        if value not in [
            None,
            "",
        ]:

            return value

    return None


# =========================================================
# DATABASE FALLBACK
# =========================================================

def build_database_fallback(
    intent,
    rows
):

    if not rows:

        return (
            "Database mein abhi is query se "
            "related koi record nahi mila."
        )

    # =====================================================
    # GENERIC RECORD FALLBACK
    #
    # This works even when table structure changes.
    # =====================================================

    lines = [
        "🔎 **Database se available information:**"
    ]

    for index, row in enumerate(
        rows[:10],
        start=1
    ):

        name = first_value(
            row,
            [
                "exam_name",
                "exam_title",
                "job_title",
                "post_name",
                "form_name",
                "document_name",
                "scholarship_name",
                "scheme_name",
                "service_name",
                "title",
                "name",
            ]
        )

        description = first_value(
            row,
            [
                "description",
                "short_description",
            ]
        )

        last_date = first_value(
            row,
            [
                "last_date",
                "last_date_to_apply",
                "application_last_date",
                "deadline",
                "last_date_to_apply",
            ]
        )

        organization = first_value(
            row,
            [
                "organization",
                "department",
                "company",
            ]
        )

        lines.append(
            f"\n{index}. "
            f"{name or 'Available Record'}"
        )

        if organization:

            lines.append(
                f"   Department/Organization: "
                f"{organization}"
            )

        if description:

            lines.append(
                f"   Description: "
                f"{description}"
            )

        if last_date:

            lines.append(
                f"   Last Date: "
                f"{last_date}"
            )

    return "\n".join(lines)


# =========================================================
# GEMINI SYSTEM PROMPT
# =========================================================

SYSTEM_PROMPT = """
You are KineticCosmos AI for a CSC citizen portal.

Answer the user in simple Hindi/Hinglish unless the user
clearly asks in English.

IMPORTANT DATABASE RULE:

The backend searches the actual database BEFORE calling you.

If DATABASE DATA contains records:

- Treat DATABASE DATA as the primary and authoritative source.
- Answer from those records.
- Do NOT replace records with generic knowledge.
- Do NOT invent missing fields.
- Do NOT invent fees.
- Do NOT invent dates.
- Do NOT invent eligibility.
- Do NOT invent URLs.
- Do NOT say that information is unavailable if matching
  database records are present.
- Clearly show the matching record.
- Mention only fields that actually exist.
- If an apply URL exists, mention it.
- If an official URL exists, mention it.

If DATABASE DATA is empty:

- You may provide general information.
- Clearly say that an exact current portal/database record
  was not found.
- Do not pretend that generic knowledge is a live database
  record.

For exam/form queries:

If the database contains a matching exam such as HTET,
CTET, NEET, JEE, CUET etc., directly present that record.

For jobs:

Show available job information such as:
- post
- organization
- qualification
- last date
- location
- apply link

ONLY if those fields exist.

For forms:

Show:
- form/document name
- category
- description
- dates
- link

ONLY if those fields exist.

For services:

Show:
- service name
- description
- charges
- required documents

ONLY if those fields exist.

For scholarships:

Show actual scholarship records and available details.

For schemes:

Show actual government scheme records.

For admit cards:

Show actual admit card records.

For results:

Show actual result records.

For applications:

ONLY use the supplied user's application records.

Never expose private database records belonging to another user.

Use concise bullets.
"""


# =========================================================
# GEMINI RESPONSE
# =========================================================

def generate_ai_response(
    text: str,
    conversation_history: Optional[list] = None,
    database_data: Optional[list] = None,
    intent: Optional[str] = None,
):

    normalized_message = normalize_text(
        text
    )

    if intent is None:

        intent, confidence = detect_intent(
            normalized_message
        )

    else:

        _, confidence = detect_intent(
            normalized_message
        )

    database_data = (
        database_data or []
    )

    # -----------------------------------------------------
    # Conversation history
    # -----------------------------------------------------

    history_text = ""

    if conversation_history:

        recent_messages = (
            conversation_history[-10:]
        )

        history_parts = []

        for item in recent_messages:

            if not isinstance(
                item,
                dict
            ):
                continue

            sender = item.get(
                "sender",
                ""
            )

            message = item.get(
                "message",
                ""
            )

            if message:

                history_parts.append(
                    f"{sender}: {message}"
                )

        history_text = "\n".join(
            history_parts
        )

    # -----------------------------------------------------
    # DB JSON
    # -----------------------------------------------------

    cleaned_data = clean_database_data(
        database_data
    )

    db_text = json.dumps(
        cleaned_data,
        ensure_ascii=False,
        default=str,
        indent=2
    )

    if not db_text:

        db_text = "[]"

    # -----------------------------------------------------
    # Prompt
    # -----------------------------------------------------

    prompt = f"""
{SYSTEM_PROMPT}

DETECTED INTENT:
{intent}

CONFIDENCE:
{confidence}

CONVERSATION HISTORY:
{history_text or "No previous conversation."}

DATABASE DATA:
{db_text}

CURRENT USER QUESTION:
{normalized_message}

Now answer the user.

IMPORTANT:

If DATABASE DATA is NOT empty:

1. Start directly with the matching database information.
2. Do not say "portal par check karein".
3. Do not say "database unavailable".
4. Do not add generic information that conflicts with
   database data.
5. Do not invent missing fields.

If DATABASE DATA is empty:

Explain that no matching current database record was found,
then provide useful general guidance if possible.

Keep the answer concise and easy to read.
"""

    try:

        response = client.models.generate_content(
            model=MODEL_NAME,
            contents=prompt,
        )

        answer = (
            response.text.strip()
            if response.text
            else
            "Sorry, abhi proper response generate nahi ho pa raha hai."
        )

        return {
            "intent": intent,
            "confidence": confidence,
            "response": answer,
            "data_source": (
                "database"
                if database_data
                else "ai"
            ),
            "data": cleaned_data,
        }

    except Exception as e:

        print(
            "Gemini API Error:",
            str(e)
        )

        # -------------------------------------------------
        # Gemini failed but DB exists
        # -------------------------------------------------

        if database_data:

            return {
                "intent": intent,
                "confidence": confidence,
                "response": build_database_fallback(
                    intent,
                    database_data
                ),
                "data_source": "database",
                "data": cleaned_data,
            }

        return {
            "intent": intent,
            "confidence": confidence,
            "response": (
                "Sorry, abhi AI service se connection "
                "mein problem aa rahi hai."
            ),
            "data_source": "ai",
            "data": [],
        }


# =========================================================
# PUBLIC RESPONSE FUNCTION
# =========================================================

def generate_response(
    text: str,
    conversation_history=None,
    session_id=None,
    user_id=None,
):

    normalized_message = normalize_text(
        text
    )

    intent, confidence = detect_intent(
        normalized_message
    )

    print(
        "================================="
    )

    print(
        "CHATBOT MESSAGE:",
        text
    )

    print(
        "NORMALIZED:",
        normalized_message
    )

    print(
        "DETECTED INTENT:",
        intent
    )

    print(
        "CONFIDENCE:",
        confidence
    )

    print(
        "USER ID:",
        user_id
    )

    print(
        "SESSION ID:",
        session_id
    )

    print(
        "================================="
    )

    # =====================================================
    # GREETING
    # =====================================================

    if intent == "greeting":

        return {
            "intent": intent,
            "confidence": confidence,
            "response": (
                "👋 Namaste! Main KineticCosmos AI hoon.\n\n"
                "Aap Government Forms, Jobs, CSC Services, "
                "Scholarships, Admit Cards, Results, "
                "Government Schemes ya Application Status "
                "ke baare mein pooch sakte hain."
            ),
            "data_source": "ai",
            "data": [],
        }

    # =====================================================
    # DATABASE FIRST
    # =====================================================

    database_data = get_database_data(
        intent=intent,
        message=normalized_message,
        user_id=user_id,
    )

    print(
        "DATABASE RECORD COUNT:",
        len(database_data)
    )

    print(
        "DATABASE SOURCE:",
        "YES" if database_data else "NO"
    )

    # =====================================================
    # AI RESPONSE USING DB
    # =====================================================

    return generate_ai_response(
        text=normalized_message,
        conversation_history=(
            conversation_history or []
        ),
        database_data=database_data,
        intent=intent,
    )