"""Default starter seed — shared by connect() auto-init and store-suite seed CLI."""

from __future__ import annotations

import json
import os
import sqlite3
from pathlib import Path
from typing import Optional

from store_db.field_defs import normalize_field_type

STARTER_DIR = Path(__file__).resolve().parent.parent / "starter" / "default"


def _skip_auto_seed() -> bool:
    return os.environ.get("STORE_SKIP_AUTO_SEED", "").strip().lower() in ("1", "true", "yes")


def is_starter_needed(conn: sqlite3.Connection) -> bool:
    """True when DB has schema but no starter sample and auto-seed is allowed.

    Only triggers when BOTH members and services counts are zero AND
    starter_applied is absent. Partially emptied DBs (e.g. members deleted
    but catalog remains) with starter_applied set will NOT re-seed; use
    manual ``seed`` CLI or a fresh STORE_DB_PATH to recover.
    """
    if _skip_auto_seed():
        return False
    row = conn.execute("SELECT 1 FROM store_meta WHERE key='starter_applied' LIMIT 1").fetchone()
    if row:
        return False
    try:
        members = int(conn.execute("SELECT COUNT(*) AS c FROM store_members").fetchone()["c"])
        services = int(conn.execute("SELECT COUNT(*) AS c FROM catalog_services").fetchone()["c"])
    except sqlite3.OperationalError:
        return False
    return members == 0 and services == 0


def apply_default_seed(conn: sqlite3.Connection, *, with_field_defs: bool = True) -> None:
    starter = STARTER_DIR
    if not starter.is_dir():
        raise FileNotFoundError("starter not found: {}".format(starter))

    seed_sql = starter / "seed.sql"
    if not seed_sql.is_file():
        raise FileNotFoundError("seed.sql not found: {}".format(seed_sql))

    conn.executescript(seed_sql.read_text(encoding="utf-8"))

    lexicon = starter / "lexicon.json"
    if lexicon.is_file():
        conn.execute(
            "INSERT OR REPLACE INTO store_meta(key, value_json) VALUES ('lexicon', ?)",
            (lexicon.read_text(encoding="utf-8").strip(),),
        )

    if with_field_defs:
        defs_path = starter / "field_defs_seed.json"
        if defs_path.is_file():
            for item in json.loads(defs_path.read_text(encoding="utf-8")):
                conn.execute(
                    """
                    INSERT OR REPLACE INTO store_custom_field_defs
                    (entity, field_key, label, field_type, options_json, sort_order, updated_at)
                    VALUES (?,?,?,?, '[]', 0, datetime('now','localtime'))
                    """,
                    (item["entity"], item["field_key"], item["label"], normalize_field_type(item["field_type"])),
                )

    conn.execute(
        "INSERT OR REPLACE INTO store_meta(key, value_json) VALUES ('starter_applied', 'true')",
    )
    conn.commit()


def ensure_starter(conn: sqlite3.Connection) -> bool:
    """Apply default starter when needed. Returns True if seed ran."""
    if not is_starter_needed(conn):
        return False
    apply_default_seed(conn, with_field_defs=True)
    return True
