import os
import subprocess
from typing import Dict, Optional

from sqlalchemy import text

from synthneura.storage.db import get_engine, resolve_db_url

DEFAULT_DB_URL = resolve_db_url()


def _latest_run(db_url: str, query: str) -> Optional[Dict[str, str]]:
    engine = get_engine(resolve_db_url(db_url))
    with engine.connect() as conn:
        result = conn.execute(
            text(
                """
                SELECT run_id, ingested_at, source, query, total, new_count,
                       updated_count, unchanged_count, failed_count
                FROM runs
                WHERE query = :query
                ORDER BY ingested_at DESC
                LIMIT 1
                """
            ),
            {"query": query},
        )
        row = result.mappings().first()
        return dict(row) if row else None


def run_pipeline(query: str, max_results: int = 25) -> Dict[str, str]:
    db_url = os.getenv("SYNTHNEURA_DB_URL", DEFAULT_DB_URL)
    sink = "postgres" if db_url else "sqlite"
    command = [
        "python",
        "-m",
        "synthneura.ui.cli",
        "--query",
        query,
        "--max-results",
        str(max_results),
        "--sink",
        sink,
    ]
    if sink == "postgres":
        command.extend(["--db-url", db_url])
    try:
        subprocess.run(command, check=True)
        run = _latest_run(db_url, query)
        payload: Dict[str, str] = {"status": "ok"}
        if run and run.get("run_id"):
            payload["run_id"] = run["run_id"]
        return payload
    except subprocess.CalledProcessError as exc:
        return {"status": "error", "detail": str(exc)}
