"""Query helpers for the local connections table.

Used by the ``my_connections`` contacts action to search 1st-degree
LinkedIn connections that have been synced locally via connection_sync.
All functions are **synchronous** and must be called via ``run_db()``.
"""

from __future__ import annotations

import time
from typing import Any

from .schema import get_db


def search_my_connections(
    query: str,
    account_id: str,
    limit: int = 25,
) -> list[dict[str, Any]]:
    """Full-text LIKE search across name, headline, company, location.

    Results are ranked by relevance: name match (4) > headline (3) >
    company (2) > location (1).
    """
    db = get_db()
    try:
        pattern = f"%{query}%"
        rows = db.execute(
            """SELECT provider_id, public_id, name, headline,
                      company, location, profile_url, synced_at,
                      CASE
                          WHEN LOWER(name) LIKE LOWER(?) THEN 4
                          WHEN LOWER(headline) LIKE LOWER(?) THEN 3
                          WHEN LOWER(company) LIKE LOWER(?) THEN 2
                          WHEN LOWER(location) LIKE LOWER(?) THEN 1
                          ELSE 0
                      END AS relevance
               FROM connections
               WHERE account_id = ?
                 AND (LOWER(name) LIKE LOWER(?)
                      OR LOWER(headline) LIKE LOWER(?)
                      OR LOWER(company) LIKE LOWER(?)
                      OR LOWER(location) LIKE LOWER(?))
               ORDER BY relevance DESC, name ASC
               LIMIT ?""",
            (
                pattern, pattern, pattern, pattern,
                account_id,
                pattern, pattern, pattern, pattern,
                limit,
            ),
        ).fetchall()
        return [dict(r) for r in rows]
    finally:
        db.close()


def list_all_connections(
    account_id: str,
    limit: int = 50,
    offset: int = 0,
) -> list[dict[str, Any]]:
    """List all locally-synced connections ordered by name."""
    db = get_db()
    try:
        rows = db.execute(
            """SELECT provider_id, public_id, name, headline,
                      company, location, profile_url, synced_at
               FROM connections
               WHERE account_id = ?
               ORDER BY name ASC
               LIMIT ? OFFSET ?""",
            (account_id, limit, offset),
        ).fetchall()
        return [dict(r) for r in rows]
    finally:
        db.close()


def get_connection_sync_status(account_id: str) -> dict[str, Any]:
    """Return sync status: count, last_synced timestamp, and age in seconds."""
    db = get_db()
    try:
        row = db.execute(
            "SELECT COUNT(*) AS cnt, MAX(synced_at) AS last_synced FROM connections WHERE account_id = ?",
            (account_id,),
        ).fetchone()
        count = row["cnt"] if row else 0
        last_synced = row["last_synced"] if row else None
        age = int(time.time()) - last_synced if last_synced else None
        return {
            "count": count,
            "last_synced": last_synced,
            "age_seconds": age,
            "synced": count > 0,
        }
    finally:
        db.close()
