import os
import sqlite3
import subprocess
from typing import Dict, Optional


def _default_db_path() -> str:
    env_path = os.getenv("SYNTHNEURA_DB_PATH")
    if env_path:
        return env_path
    repo_root = os.path.abspath(
        os.path.join(os.path.dirname(__file__), "..", "..", "..", "..")
    )
    return os.path.join(repo_root, "trials.db")


DEFAULT_DB_PATH = _default_db_path()


def _latest_run(db_path: str, query: str) -> Optional[Dict[str, str]]:
    if not os.path.exists(db_path):
        return None
    conn = sqlite3.connect(db_path)
    conn.row_factory = sqlite3.Row
    try:
        row = conn.execute(
            """
            SELECT run_id, ingested_at, source, query, total, new_count, updated_count,
                   unchanged_count, failed_count
            FROM runs
            WHERE query = ?
            ORDER BY ingested_at DESC
            LIMIT 1
            """,
            (query,),
        ).fetchone()
        return dict(row) if row else None
    finally:
        conn.close()


def run_pipeline(query: str, max_results: int = 25) -> Dict[str, str]:
    command = [
        "python",
        "-m",
        "synthneura.ui.cli",
        "--query",
        query,
        "--max-results",
        str(max_results),
    ]
    try:
        subprocess.run(command, check=True)
        db_path = os.getenv("SYNTHNEURA_DB_PATH", DEFAULT_DB_PATH)
        run = _latest_run(db_path, 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)}
