"""Shared SQLite schema for insurance skills."""
from __future__ import annotations

import os
import sqlite3
from pathlib import Path


def default_db_path() -> Path:
    base = Path.home() / ".config" / "insurance"
    base.mkdir(parents=True, exist_ok=True)
    return base / "insurance.sqlite3"


def get_db_path() -> Path:
    for key in ("INSURANCE_DB_PATH", "INSURANCE_SCHEDULE_DB_PATH"):
        p = os.environ.get(key)
        if p:
            path = Path(p)
            path.parent.mkdir(parents=True, exist_ok=True)
            return path
    return default_db_path()


def connect() -> sqlite3.Connection:
    conn = sqlite3.connect(str(get_db_path()))
    conn.row_factory = sqlite3.Row
    conn.execute("PRAGMA foreign_keys=ON")
    init_schema(conn)
    return conn


def init_schema(conn: sqlite3.Connection) -> None:
    conn.executescript(
        """
        CREATE TABLE IF NOT EXISTS customers (
            id TEXT PRIMARY KEY,
            name TEXT NOT NULL,
            phone TEXT,
            age INTEGER,
            gender TEXT,
            income REAL,
            household_json TEXT NOT NULL DEFAULT '{}',
            occupation TEXT,
            birthday TEXT,
            tags_json TEXT NOT NULL DEFAULT '[]',
            fields_json TEXT NOT NULL DEFAULT '{}',
            status TEXT NOT NULL DEFAULT 'active',
            created_at TEXT NOT NULL DEFAULT (datetime('now','localtime')),
            updated_at TEXT NOT NULL DEFAULT (datetime('now','localtime'))
        );
        CREATE INDEX IF NOT EXISTS idx_customers_phone ON customers(phone);
        CREATE INDEX IF NOT EXISTS idx_customers_birthday ON customers(birthday);

        CREATE TABLE IF NOT EXISTS policies (
            id TEXT PRIMARY KEY,
            customer_id TEXT NOT NULL REFERENCES customers(id) ON DELETE RESTRICT,
            company TEXT NOT NULL,
            product_name TEXT NOT NULL,
            product_type TEXT NOT NULL,
            coverage REAL NOT NULL DEFAULT 0,
            premium REAL NOT NULL DEFAULT 0,
            pay_period TEXT,
            effective_date TEXT NOT NULL,
            expire_date TEXT,
            next_pay_date TEXT,
            insured_name TEXT,
            beneficiary TEXT,
            notes TEXT,
            status TEXT NOT NULL DEFAULT 'active',
            created_at TEXT NOT NULL DEFAULT (datetime('now','localtime')),
            updated_at TEXT NOT NULL DEFAULT (datetime('now','localtime'))
        );
        CREATE INDEX IF NOT EXISTS idx_policies_customer ON policies(customer_id, status);
        CREATE INDEX IF NOT EXISTS idx_policies_expire ON policies(expire_date, status);
        CREATE INDEX IF NOT EXISTS idx_policies_next_pay ON policies(next_pay_date, status);
        CREATE INDEX IF NOT EXISTS idx_policies_type ON policies(product_type, status);

        CREATE TABLE IF NOT EXISTS followups (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            customer_id TEXT NOT NULL REFERENCES customers(id) ON DELETE CASCADE,
            content TEXT NOT NULL,
            next_step TEXT,
            next_date TEXT,
            channel TEXT,
            created_at TEXT NOT NULL DEFAULT (datetime('now','localtime'))
        );
        CREATE INDEX IF NOT EXISTS idx_followups_customer ON followups(customer_id, created_at DESC);

        CREATE TABLE IF NOT EXISTS customer_fields (
            name TEXT PRIMARY KEY,
            type TEXT NOT NULL DEFAULT 'text'
        );

        CREATE TABLE IF NOT EXISTS products (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL UNIQUE,
            company TEXT NOT NULL,
            product_type TEXT NOT NULL,
            coverage_min REAL,
            coverage_max REAL,
            premium_min REAL,
            premium_max REAL,
            age_min INTEGER,
            age_max INTEGER,
            waiting_period TEXT,
            deductible TEXT,
            renewal_terms TEXT,
            highlights_json TEXT NOT NULL DEFAULT '[]',
            target_audience TEXT,
            file_path TEXT,
            raw_text TEXT,
            status TEXT NOT NULL DEFAULT 'active',
            created_at TEXT NOT NULL DEFAULT (datetime('now','localtime')),
            updated_at TEXT NOT NULL DEFAULT (datetime('now','localtime'))
        );
        CREATE INDEX IF NOT EXISTS idx_products_type ON products(product_type, status);
        CREATE INDEX IF NOT EXISTS idx_products_company ON products(company, status);

        CREATE TABLE IF NOT EXISTS product_analysis_cache (
            product_id INTEGER PRIMARY KEY REFERENCES products(id) ON DELETE CASCADE,
            key_terms_json TEXT,
            selling_points_json TEXT,
            fit_audience_json TEXT,
            pitch_script TEXT,
            analyzed_at TEXT NOT NULL DEFAULT (datetime('now','localtime'))
        );

        CREATE TABLE IF NOT EXISTS deals (
            id TEXT PRIMARY KEY,
            customer_id TEXT NOT NULL,
            customer_name TEXT,
            product_name TEXT,
            product_type TEXT,
            stage TEXT NOT NULL,
            estimated_premium REAL NOT NULL DEFAULT 0,
            actual_premium REAL,
            expected_close_date TEXT,
            closed_at TEXT,
            lost_reason TEXT,
            lost_note TEXT,
            note TEXT,
            created_at TEXT NOT NULL DEFAULT (datetime('now','localtime')),
            updated_at TEXT NOT NULL DEFAULT (datetime('now','localtime'))
        );
        CREATE INDEX IF NOT EXISTS idx_deals_stage ON deals(stage, expected_close_date);
        CREATE INDEX IF NOT EXISTS idx_deals_customer ON deals(customer_id);

        CREATE TABLE IF NOT EXISTS deal_stage_log (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            deal_id TEXT NOT NULL REFERENCES deals(id) ON DELETE CASCADE,
            from_stage TEXT,
            to_stage TEXT NOT NULL,
            note TEXT,
            created_at TEXT NOT NULL DEFAULT (datetime('now','localtime'))
        );
        CREATE INDEX IF NOT EXISTS idx_stage_log_deal ON deal_stage_log(deal_id, created_at);

        CREATE TABLE IF NOT EXISTS monthly_targets (
            month TEXT PRIMARY KEY,
            target_premium REAL NOT NULL,
            note TEXT,
            created_at TEXT NOT NULL DEFAULT (datetime('now','localtime')),
            updated_at TEXT NOT NULL DEFAULT (datetime('now','localtime'))
        );

        CREATE TABLE IF NOT EXISTS sent_reminders (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            reminder_type TEXT NOT NULL,
            target_id TEXT NOT NULL,
            bucket TEXT NOT NULL,
            sent_at TEXT NOT NULL DEFAULT (datetime('now','localtime')),
            status TEXT NOT NULL DEFAULT 'sent',
            note TEXT,
            UNIQUE (reminder_type, target_id, bucket)
        );
        CREATE INDEX IF NOT EXISTS idx_sent_target ON sent_reminders(target_id, reminder_type);
        """
    )
    conn.commit()
