"""SQL interview patterns on a tiny SQLite dataset (needs SQLite 3.25+ for window functions).

Run:  python3 src/sql_exercises.py     # prints every query and its result
"""
from __future__ import annotations

import sqlite3

SCHEMA = """
CREATE TABLE employees (id INTEGER PRIMARY KEY, name TEXT, dept TEXT, salary INTEGER);
CREATE TABLE users (user_id INTEGER PRIMARY KEY, signup_date TEXT, country TEXT);
CREATE TABLE logins (user_id INTEGER, login_date TEXT);
CREATE TABLE orders (order_id INTEGER PRIMARY KEY, user_id INTEGER, order_date TEXT, amount REAL);
CREATE TABLE funnel (user_id INTEGER, step TEXT);
"""

SEED = """
INSERT INTO employees VALUES
 (1,'Ana','eng',180),(2,'Bo','eng',150),(3,'Cy','eng',150),(4,'Di','eng',120),
 (5,'Ed','sales',90),(6,'Fa','sales',110),(7,'Gu','ops',70);
INSERT INTO users VALUES
 (1,'2026-01-01','US'),(2,'2026-01-01','IN'),(3,'2026-01-02','US'),(4,'2026-01-02','DE');
INSERT INTO logins VALUES
 (1,'2026-01-01'),(1,'2026-01-02'),(1,'2026-01-03'),(1,'2026-01-05'),
 (2,'2026-01-01'),
 (3,'2026-01-02'),(3,'2026-01-03'),
 (4,'2026-01-02'),(4,'2026-01-09');
INSERT INTO orders VALUES
 (1,1,'2026-01-01',20),(2,1,'2026-01-02',35),(3,2,'2026-01-02',10),(4,3,'2026-01-03',50),
 (5,3,'2026-01-04',5),(6,4,'2026-01-05',40),(7,1,'2026-01-06',15),(8,2,'2026-01-07',25);
INSERT INTO funnel VALUES
 (1,'view'),(1,'cart'),(1,'checkout'),(2,'view'),(2,'cart'),(3,'view'),(4,'view'),(4,'cart'),(4,'checkout');
"""

QUERIES: dict[str, str] = {
    # Q: Second highest DISTINCT salary (NULL if none). Pattern: DISTINCT + OFFSET, or DENSE_RANK.
    "second_highest_salary": """
        SELECT (SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET 1) AS second_highest;
    """,
    # Q: Top 2 earners per department, ties included. Pattern: DENSE_RANK over a partition.
    "top2_per_dept": """
        SELECT dept, name, salary FROM (
          SELECT dept, name, salary,
                 DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS rnk
          FROM employees)
        WHERE rnk <= 2
        ORDER BY dept, salary DESC, name;
    """,
    # Q: Day-1 retention by signup cohort. Pattern: LEFT JOIN on a shifted date, then average a 0/1 flag.
    "day1_retention": """
        SELECT u.signup_date,
               COUNT(*) AS cohort_size,
               ROUND(AVG(CASE WHEN l.user_id IS NOT NULL THEN 1.0 ELSE 0 END), 2) AS d1_retention
        FROM users u
        LEFT JOIN logins l
          ON l.user_id = u.user_id AND l.login_date = DATE(u.signup_date, '+1 day')
        GROUP BY u.signup_date
        ORDER BY u.signup_date;
    """,
    # Q: Longest streak of consecutive login days per user. Pattern: gaps and islands
    # (date minus row_number is constant inside a streak).
    "longest_streak": """
        WITH numbered AS (
          SELECT user_id, login_date,
                 JULIANDAY(login_date) - ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY login_date) AS grp
          FROM (SELECT DISTINCT user_id, login_date FROM logins)),
        streaks AS (
          SELECT user_id, COUNT(*) AS len FROM numbered GROUP BY user_id, grp)
        SELECT user_id, MAX(len) AS longest_streak FROM streaks GROUP BY user_id ORDER BY user_id;
    """,
    # Q: Running total of revenue by day, and 3-day rolling average. Pattern: window frames.
    "running_and_rolling": """
        WITH daily AS (SELECT order_date, SUM(amount) AS revenue FROM orders GROUP BY order_date)
        SELECT order_date, revenue,
               SUM(revenue) OVER (ORDER BY order_date) AS running_total,
               ROUND(AVG(revenue) OVER (ORDER BY order_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 2) AS rolling_3
        FROM daily ORDER BY order_date;
    """,
    # Q: Funnel conversion from view -> cart -> checkout. Pattern: conditional aggregation.
    "funnel_conversion": """
        SELECT SUM(step = 'view') AS viewed,
               SUM(step = 'cart') AS carted,
               SUM(step = 'checkout') AS checked_out,
               ROUND(1.0 * SUM(step = 'checkout') / SUM(step = 'view'), 2) AS view_to_checkout
        FROM funnel;
    """,
    # Q: Each user's first order and the gap (days) to their second order. Pattern: LEAD / ROW_NUMBER.
    "first_order_and_gap": """
        WITH ranked AS (
          SELECT user_id, order_date,
                 ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY order_date) AS rn,
                 LEAD(order_date) OVER (PARTITION BY user_id ORDER BY order_date) AS next_date
          FROM orders)
        SELECT user_id, order_date AS first_order,
               CAST(JULIANDAY(next_date) - JULIANDAY(order_date) AS INTEGER) AS days_to_second
        FROM ranked WHERE rn = 1 ORDER BY user_id;
    """,
    # Q: Median order amount without a MEDIAN function. Pattern: ROW_NUMBER + COUNT.
    "median_order": """
        WITH o AS (
          SELECT amount, ROW_NUMBER() OVER (ORDER BY amount) AS rn, COUNT(*) OVER () AS n FROM orders)
        SELECT AVG(amount) AS median FROM o WHERE rn IN ((n + 1) / 2, (n + 2) / 2);
    """,
    # Q: Users who ordered on 2+ different days but never spent more than 40 in one order. Pattern: HAVING.
    "repeat_small_spenders": """
        SELECT user_id FROM orders
        GROUP BY user_id
        HAVING COUNT(DISTINCT order_date) >= 2 AND MAX(amount) <= 40
        ORDER BY user_id;
    """,
}


def connect() -> sqlite3.Connection:
    con = sqlite3.connect(":memory:")
    con.executescript(SCHEMA + SEED)
    return con


def run(name: str, con: sqlite3.Connection | None = None) -> list[tuple]:
    con = con or connect()
    return con.execute(QUERIES[name]).fetchall()


if __name__ == "__main__":
    db = connect()
    for key in QUERIES:
        print(f"-- {key}")
        for row in run(key, db):
            print(row)
        print()
