"""A conservative, in-memory Python/SQLite deduplication example. Python 3.10+."""
import json
from pathlib import Path
import sqlite3
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit

TRACKING = {"utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"}


def comparison_url(url):
    parts = urlsplit(url)
    query = [(key, value) for key, value in parse_qsl(parts.query, keep_blank_values=True)
             if key.lower() not in TRACKING]
    return urlunsplit((parts.scheme.lower(), parts.netloc.lower(), parts.path,
                      urlencode(query), parts.fragment))


def database():
    con = sqlite3.connect(":memory:")
    con.execute("PRAGMA foreign_keys = ON")
    con.executescript("""
        CREATE TABLE openings (
            id INTEGER PRIMARY KEY,
            employer TEXT NOT NULL,
            employer_url TEXT NOT NULL,
            saved INTEGER NOT NULL DEFAULT 0 CHECK(saved IN (0, 1)),
            user_note TEXT NOT NULL DEFAULT '',
            UNIQUE(employer, employer_url)
        );
        CREATE TABLE sightings (
            source TEXT NOT NULL,
            employer TEXT NOT NULL,
            posting_id TEXT NOT NULL,
            opening_id INTEGER NOT NULL REFERENCES openings(id),
            original_url TEXT NOT NULL,
            title TEXT NOT NULL,
            location TEXT NOT NULL,
            description TEXT NOT NULL,
            PRIMARY KEY(source, employer, posting_id)
        );
    """)
    return con


def ingest(con, row):
    # The fixture supplies a verified employer destination. Never infer it from a title.
    required = ["source", "employer", "posting_id", "employer_url", "original_url",
                "title", "location", "description"]
    if any(not isinstance(row.get(k), str) or not row[k] for k in required):
        raise ValueError("missing identity or source fields: retain for manual review")
    canonical = comparison_url(row["employer_url"])
    identity = (row["source"], row["employer"], row["posting_id"])
    with con:
        previous = con.execute(
            "SELECT opening_id FROM sightings WHERE source=? AND employer=? AND posting_id=?",
            identity).fetchone()
        if previous:
            opening_id = previous[0]
        else:
            con.execute("""INSERT INTO openings(employer, employer_url) VALUES (?, ?)
                ON CONFLICT(employer, employer_url) DO NOTHING""", (row["employer"], canonical))
            opening_id = con.execute(
                "SELECT id FROM openings WHERE employer=? AND employer_url=?",
                (row["employer"], canonical)).fetchone()[0]
        con.execute("""INSERT INTO sightings VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ON CONFLICT(source, employer, posting_id) DO UPDATE SET
                original_url=excluded.original_url, title=excluded.title,
                location=excluded.location, description=excluded.description""",
            (*identity, opening_id, row["original_url"], row["title"], row["location"], row["description"]))
    return opening_id


def demo():
    rows = json.loads(Path(__file__).with_name("listings.json").read_text(encoding="utf-8"))
    con = database()
    try:
        first = ingest(con, rows[0])
        con.execute("UPDATE openings SET saved=1, user_note=? WHERE id=?", ("Review tomorrow", first))
        con.commit()
        for row in rows[1:]:
            ingest(con, row)
        before = con.execute("SELECT count(*) FROM openings").fetchone()[0]
        for row in rows:
            ingest(con, row)
        return {
            "input_rows": len(rows), "openings": before,
            "sightings": con.execute("SELECT count(*) FROM sightings").fetchone()[0],
            "openings_after_replay": con.execute("SELECT count(*) FROM openings").fetchone()[0],
            "saved_state": list(con.execute("SELECT saved, user_note FROM openings WHERE id=?", (first,)).fetchone()),
            "latest_description": con.execute("SELECT description FROM sightings WHERE source='ats' AND employer='example-labs' AND posting_id='4821'").fetchone()[0]
        }
    finally:
        con.close()


if __name__ == "__main__":
    print(json.dumps(demo(), indent=2))
