"""SalesOS schema: deal forecasts, proposals, token usage, Slack, model pricing.

These tables support the SalesOS add-on features. Only created when
SalesOS is enabled in the deployment.
"""

SQLITE_DDL = """
CREATE TABLE IF NOT EXISTS token_usage (
    id TEXT PRIMARY KEY,
    agent_id TEXT,
    session_id TEXT,
    work_item_id TEXT,
    model TEXT NOT NULL,
    input_tokens INTEGER NOT NULL DEFAULT 0,
    output_tokens INTEGER NOT NULL DEFAULT 0,
    cost_usd REAL NOT NULL DEFAULT 0.0,
    created_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS model_pricing (
    model TEXT PRIMARY KEY,
    input_cost_per_million REAL NOT NULL,
    output_cost_per_million REAL NOT NULL,
    updated_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS deal_forecasts (
    id TEXT PRIMARY KEY,
    deal_id TEXT NOT NULL,
    deal_name TEXT NOT NULL,
    close_probability REAL NOT NULL,
    close_probability_pct INTEGER NOT NULL,
    confidence_band_low REAL NOT NULL,
    confidence_band_high REAL NOT NULL,
    meddpicc_score REAL NOT NULL DEFAULT 0.0,
    engagement_score REAL NOT NULL DEFAULT 0.0,
    momentum TEXT NOT NULL,
    risk_factors TEXT,
    positive_signals TEXT,
    forecast_method TEXT NOT NULL,
    model_version TEXT NOT NULL,
    created_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS deal_forecast_models (
    id TEXT PRIMARY KEY,
    model_version TEXT NOT NULL,
    model_json TEXT NOT NULL,
    training_samples INTEGER NOT NULL,
    training_accuracy REAL NOT NULL,
    created_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS proposals (
    id TEXT PRIMARY KEY,
    template_id TEXT NOT NULL,
    account_name TEXT NOT NULL,
    sections TEXT NOT NULL,
    meddpicc_completeness REAL NOT NULL DEFAULT 0.0,
    metadata TEXT,
    generated_at TEXT NOT NULL,
    created_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS slack_channels (
    id TEXT PRIMARY KEY,
    channel_name TEXT NOT NULL UNIQUE,
    webhook_url TEXT NOT NULL,
    alert_types TEXT NOT NULL DEFAULT '[]',
    enabled INTEGER NOT NULL DEFAULT 1,
    created_at TEXT DEFAULT (datetime('now')),
    updated_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS slack_notifications (
    id TEXT PRIMARY KEY,
    alert_type TEXT NOT NULL,
    channel_name TEXT NOT NULL,
    payload TEXT NOT NULL,
    success INTEGER NOT NULL DEFAULT 0,
    error_message TEXT,
    created_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS webhooks (
    id TEXT PRIMARY KEY,
    url TEXT NOT NULL,
    event_types TEXT NOT NULL DEFAULT '[]',
    active INTEGER NOT NULL DEFAULT 1,
    created_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS events (
    id TEXT PRIMARY KEY,
    event_type TEXT NOT NULL,
    payload TEXT NOT NULL,
    created_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS domains (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL UNIQUE,
    description TEXT,
    created_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS domain_files (
    id TEXT PRIMARY KEY,
    domain_id TEXT NOT NULL REFERENCES domains(id),
    file_path TEXT NOT NULL,
    created_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS salesos_accounts (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL,
    data TEXT,
    created_at TEXT DEFAULT (datetime('now')),
    updated_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS salesos_contacts (
    id TEXT PRIMARY KEY,
    account_id TEXT REFERENCES salesos_accounts(id),
    name TEXT NOT NULL,
    data TEXT,
    created_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS salesos_hunting_list (
    id TEXT PRIMARY KEY,
    account_id TEXT REFERENCES salesos_accounts(id),
    priority INTEGER DEFAULT 0,
    data TEXT,
    created_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS salesos_meddpicc_scores (
    id TEXT PRIMARY KEY,
    account_id TEXT REFERENCES salesos_accounts(id),
    scores TEXT NOT NULL,
    created_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS salesos_research_docs (
    id TEXT PRIMARY KEY,
    account_id TEXT REFERENCES salesos_accounts(id),
    doc_type TEXT NOT NULL,
    content TEXT NOT NULL,
    created_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS salesos_snapshots (
    id TEXT PRIMARY KEY,
    account_id TEXT REFERENCES salesos_accounts(id),
    snapshot_data TEXT NOT NULL,
    created_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS salesos_trigger_alerts (
    id TEXT PRIMARY KEY,
    account_id TEXT REFERENCES salesos_accounts(id),
    alert_type TEXT NOT NULL,
    content TEXT NOT NULL,
    created_at TEXT DEFAULT (datetime('now'))
);

-- SalesOS 4.x tables

CREATE TABLE IF NOT EXISTS salesos_findings (
    id TEXT PRIMARY KEY,
    account_id TEXT REFERENCES salesos_accounts(id),
    domain TEXT NOT NULL,
    category TEXT NOT NULL,
    title TEXT NOT NULL,
    detail TEXT NOT NULL,
    confidence TEXT NOT NULL DEFAULT 'EMERGING',
    source_url TEXT,
    source_type TEXT,
    discovered_by TEXT,
    discovered_at TEXT DEFAULT (datetime('now')),
    freshness_days INTEGER NOT NULL DEFAULT 30,
    status TEXT NOT NULL DEFAULT 'current',
    meddpicc_elements TEXT DEFAULT '[]',
    superseded_by TEXT
);

CREATE TABLE IF NOT EXISTS salesos_vendor_stack (
    id TEXT PRIMARY KEY,
    account_id TEXT REFERENCES salesos_accounts(id),
    finding_id TEXT REFERENCES salesos_findings(id),
    layer TEXT NOT NULL,
    vendor TEXT NOT NULL,
    product TEXT,
    model_series TEXT,
    deployment_age_years REAL,
    eol_date TEXT,
    contract_expiry TEXT,
    partner_var TEXT,
    notes TEXT,
    confidence TEXT NOT NULL DEFAULT 'EMERGING',
    discovered_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS salesos_funding_sources (
    id TEXT PRIMARY KEY,
    account_id TEXT REFERENCES salesos_accounts(id),
    finding_id TEXT REFERENCES salesos_findings(id),
    program_name TEXT NOT NULL,
    tier TEXT NOT NULL,
    timeframe TEXT NOT NULL,
    amount REAL,
    discount_rate REAL,
    filing_status TEXT,
    deadline TEXT,
    fiscal_year TEXT,
    notes TEXT,
    confidence TEXT NOT NULL DEFAULT 'EMERGING',
    discovered_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS salesos_procurement_history (
    id TEXT PRIMARY KEY,
    account_id TEXT REFERENCES salesos_accounts(id),
    finding_id TEXT REFERENCES salesos_findings(id),
    description TEXT NOT NULL,
    vehicle TEXT,
    amount REAL,
    procurement_date TEXT,
    status TEXT,
    vendor_awarded TEXT,
    notes TEXT,
    confidence TEXT NOT NULL DEFAULT 'EMERGING',
    discovered_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS salesos_compliance (
    id TEXT PRIMARY KEY,
    account_id TEXT REFERENCES salesos_accounts(id),
    finding_id TEXT REFERENCES salesos_findings(id),
    framework TEXT NOT NULL,
    status TEXT,
    gap_description TEXT,
    deadline TEXT,
    notes TEXT,
    confidence TEXT NOT NULL DEFAULT 'EMERGING',
    discovered_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS salesos_legislative (
    id TEXT PRIMARY KEY,
    account_id TEXT REFERENCES salesos_accounts(id),
    finding_id TEXT REFERENCES salesos_findings(id),
    title TEXT NOT NULL,
    jurisdiction TEXT NOT NULL,
    bill_number TEXT,
    status TEXT,
    impact_description TEXT,
    effective_date TEXT,
    notes TEXT,
    confidence TEXT NOT NULL DEFAULT 'EMERGING',
    discovered_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS salesos_broadband_projects (
    id TEXT PRIMARY KEY,
    account_id TEXT REFERENCES salesos_accounts(id),
    finding_id TEXT REFERENCES salesos_findings(id),
    name TEXT NOT NULL,
    program TEXT,
    status TEXT,
    amount REAL,
    timeline TEXT,
    notes TEXT,
    confidence TEXT NOT NULL DEFAULT 'EMERGING',
    discovered_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS salesos_meetings (
    id TEXT PRIMARY KEY,
    account_id TEXT REFERENCES salesos_accounts(id),
    meeting_date TEXT NOT NULL,
    attendees TEXT DEFAULT '[]',
    purpose TEXT,
    notes TEXT,
    meddpicc_gaps_addressed TEXT DEFAULT '[]',
    created_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS salesos_meddpicc_element_scores (
    id TEXT PRIMARY KEY,
    account_id TEXT REFERENCES salesos_accounts(id),
    snapshot_id TEXT REFERENCES salesos_meddpicc_scores(id),
    element TEXT NOT NULL,
    score INTEGER NOT NULL DEFAULT 0,
    status TEXT NOT NULL DEFAULT 'unknown',
    evidence_summary TEXT DEFAULT '',
    evidence_finding_ids TEXT DEFAULT '[]',
    gap_action TEXT,
    discovery_question TEXT,
    created_at TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS salesos_stage_progress (
    account_id TEXT PRIMARY KEY REFERENCES salesos_accounts(id),
    current_stage INTEGER NOT NULL DEFAULT 0,
    stage_entered_at TEXT DEFAULT (datetime('now')),
    required_fields TEXT DEFAULT '[]',
    suggested_fields TEXT DEFAULT '[]',
    fields_completed TEXT DEFAULT '{}',
    last_activity TEXT DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS salesos_discovery_questions (
    id TEXT PRIMARY KEY,
    account_id TEXT REFERENCES salesos_accounts(id),
    question_text TEXT NOT NULL,
    why_needed TEXT NOT NULL,
    target_field TEXT NOT NULL,
    priority TEXT NOT NULL DEFAULT 'SUGGESTED',
    stage_relevant INTEGER NOT NULL,
    status TEXT NOT NULL DEFAULT 'OPEN',
    answer TEXT,
    answered_at TEXT,
    created_at TEXT DEFAULT (datetime('now'))
);

-- SalesOS 4.x indexes
CREATE INDEX IF NOT EXISTS idx_salesos_findings_account ON salesos_findings(account_id);
CREATE INDEX IF NOT EXISTS idx_salesos_findings_domain ON salesos_findings(domain);
CREATE INDEX IF NOT EXISTS idx_salesos_vendor_stack_account ON salesos_vendor_stack(account_id);
CREATE INDEX IF NOT EXISTS idx_salesos_vendor_stack_layer ON salesos_vendor_stack(layer);
CREATE INDEX IF NOT EXISTS idx_salesos_funding_account ON salesos_funding_sources(account_id);
CREATE INDEX IF NOT EXISTS idx_salesos_procurement_account ON salesos_procurement_history(account_id);
CREATE INDEX IF NOT EXISTS idx_salesos_compliance_account ON salesos_compliance(account_id);
CREATE INDEX IF NOT EXISTS idx_salesos_compliance_framework ON salesos_compliance(framework);
CREATE INDEX IF NOT EXISTS idx_salesos_legislative_account ON salesos_legislative(account_id);
CREATE INDEX IF NOT EXISTS idx_salesos_legislative_jurisdiction ON salesos_legislative(jurisdiction);
CREATE INDEX IF NOT EXISTS idx_salesos_broadband_account ON salesos_broadband_projects(account_id);
CREATE INDEX IF NOT EXISTS idx_salesos_meetings_account ON salesos_meetings(account_id);
CREATE INDEX IF NOT EXISTS idx_salesos_meetings_date ON salesos_meetings(meeting_date);
CREATE INDEX IF NOT EXISTS idx_salesos_meddpicc_elements_account ON salesos_meddpicc_element_scores(account_id);
CREATE INDEX IF NOT EXISTS idx_salesos_discovery_account ON salesos_discovery_questions(account_id);
CREATE INDEX IF NOT EXISTS idx_salesos_discovery_status ON salesos_discovery_questions(status);
"""

CRDB_DDL = """
CREATE TABLE IF NOT EXISTS token_usage (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    agent_id UUID,
    session_id UUID,
    work_item_id UUID,
    model TEXT NOT NULL,
    input_tokens INT NOT NULL DEFAULT 0,
    output_tokens INT NOT NULL DEFAULT 0,
    cost_usd DECIMAL(12, 6) NOT NULL DEFAULT 0.0,
    created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS model_pricing (
    model TEXT PRIMARY KEY,
    input_cost_per_million DECIMAL(10, 4) NOT NULL,
    output_cost_per_million DECIMAL(10, 4) NOT NULL,
    updated_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS deal_forecasts (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    deal_id TEXT NOT NULL,
    deal_name TEXT NOT NULL,
    close_probability DECIMAL(5,4) NOT NULL CHECK (close_probability >= 0 AND close_probability <= 1),
    close_probability_pct INT NOT NULL CHECK (close_probability_pct >= 0 AND close_probability_pct <= 100),
    confidence_band_low DECIMAL(5,4) NOT NULL CHECK (confidence_band_low >= 0 AND confidence_band_low <= 1),
    confidence_band_high DECIMAL(5,4) NOT NULL CHECK (confidence_band_high >= 0 AND confidence_band_high <= 1),
    meddpicc_score DECIMAL(5,4) NOT NULL DEFAULT 0.0,
    engagement_score DECIMAL(5,4) NOT NULL DEFAULT 0.0,
    momentum TEXT NOT NULL CHECK (momentum IN ('accelerating', 'steady', 'stalling', 'stalled')),
    risk_factors JSONB,
    positive_signals JSONB,
    forecast_method TEXT NOT NULL CHECK (forecast_method IN ('rule_based', 'trained_model')),
    model_version TEXT NOT NULL,
    created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS deal_forecast_models (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    model_version TEXT NOT NULL,
    model_json JSONB NOT NULL,
    training_samples INT NOT NULL,
    training_accuracy DECIMAL(5,4) NOT NULL,
    created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS proposals (
    id TEXT PRIMARY KEY,
    template_id TEXT NOT NULL,
    account_name TEXT NOT NULL,
    sections JSONB NOT NULL,
    meddpicc_completeness DECIMAL(5,4) NOT NULL DEFAULT 0.0,
    metadata JSONB,
    generated_at TEXT NOT NULL,
    created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS slack_channels (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    channel_name TEXT NOT NULL UNIQUE,
    webhook_url TEXT NOT NULL,
    alert_types JSONB NOT NULL DEFAULT '[]',
    enabled BOOLEAN NOT NULL DEFAULT true,
    created_at TIMESTAMPTZ DEFAULT now(),
    updated_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS slack_notifications (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    alert_type TEXT NOT NULL,
    channel_name TEXT NOT NULL,
    payload JSONB NOT NULL,
    success BOOLEAN NOT NULL DEFAULT false,
    error_message TEXT,
    created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS webhooks (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    url TEXT NOT NULL,
    event_types JSONB NOT NULL DEFAULT '[]',
    active BOOLEAN NOT NULL DEFAULT true,
    created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS events (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    event_type TEXT NOT NULL,
    payload JSONB NOT NULL,
    created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS domains (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name TEXT NOT NULL UNIQUE,
    description TEXT,
    created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS domain_files (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    domain_id UUID NOT NULL REFERENCES domains(id),
    file_path TEXT NOT NULL,
    created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS salesos_accounts (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name TEXT NOT NULL,
    data JSONB,
    created_at TIMESTAMPTZ DEFAULT now(),
    updated_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS salesos_contacts (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    account_id UUID REFERENCES salesos_accounts(id),
    name TEXT NOT NULL,
    data JSONB,
    created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS salesos_hunting_list (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    account_id UUID REFERENCES salesos_accounts(id),
    priority INT DEFAULT 0,
    data JSONB,
    created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS salesos_meddpicc_scores (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    account_id UUID REFERENCES salesos_accounts(id),
    scores JSONB NOT NULL,
    created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS salesos_research_docs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    account_id UUID REFERENCES salesos_accounts(id),
    doc_type TEXT NOT NULL,
    content TEXT NOT NULL,
    created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS salesos_snapshots (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    account_id UUID REFERENCES salesos_accounts(id),
    snapshot_data JSONB NOT NULL,
    created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS salesos_trigger_alerts (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    account_id UUID REFERENCES salesos_accounts(id),
    alert_type TEXT NOT NULL,
    content TEXT NOT NULL,
    created_at TIMESTAMPTZ DEFAULT now()
);

-- SalesOS 4.x tables

CREATE TABLE IF NOT EXISTS salesos_findings (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    account_id UUID REFERENCES salesos_accounts(id),
    domain TEXT NOT NULL,
    category TEXT NOT NULL,
    title TEXT NOT NULL,
    detail TEXT NOT NULL,
    confidence TEXT NOT NULL DEFAULT 'EMERGING' CHECK (confidence IN ('EMERGING', 'LIKELY', 'CONFIRMED')),
    source_url TEXT,
    source_type TEXT,
    discovered_by TEXT,
    discovered_at TIMESTAMPTZ DEFAULT now(),
    freshness_days INT NOT NULL DEFAULT 30,
    status TEXT NOT NULL DEFAULT 'current' CHECK (status IN ('current', 'superseded', 'archived')),
    meddpicc_elements JSONB DEFAULT '[]',
    superseded_by UUID
);

CREATE TABLE IF NOT EXISTS salesos_vendor_stack (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    account_id UUID REFERENCES salesos_accounts(id),
    finding_id UUID REFERENCES salesos_findings(id),
    layer TEXT NOT NULL,
    vendor TEXT NOT NULL,
    product TEXT,
    model_series TEXT,
    deployment_age_years DECIMAL(5,2),
    eol_date DATE,
    contract_expiry DATE,
    partner_var TEXT,
    notes TEXT,
    confidence TEXT NOT NULL DEFAULT 'EMERGING' CHECK (confidence IN ('EMERGING', 'LIKELY', 'CONFIRMED')),
    discovered_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS salesos_funding_sources (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    account_id UUID REFERENCES salesos_accounts(id),
    finding_id UUID REFERENCES salesos_findings(id),
    program_name TEXT NOT NULL,
    tier TEXT NOT NULL,
    timeframe TEXT NOT NULL,
    amount DECIMAL(14,2),
    discount_rate DECIMAL(5,4),
    filing_status TEXT,
    deadline DATE,
    fiscal_year TEXT,
    notes TEXT,
    confidence TEXT NOT NULL DEFAULT 'EMERGING' CHECK (confidence IN ('EMERGING', 'LIKELY', 'CONFIRMED')),
    discovered_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS salesos_procurement_history (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    account_id UUID REFERENCES salesos_accounts(id),
    finding_id UUID REFERENCES salesos_findings(id),
    description TEXT NOT NULL,
    vehicle TEXT,
    amount DECIMAL(14,2),
    procurement_date DATE,
    status TEXT,
    vendor_awarded TEXT,
    notes TEXT,
    confidence TEXT NOT NULL DEFAULT 'EMERGING' CHECK (confidence IN ('EMERGING', 'LIKELY', 'CONFIRMED')),
    discovered_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS salesos_compliance (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    account_id UUID REFERENCES salesos_accounts(id),
    finding_id UUID REFERENCES salesos_findings(id),
    framework TEXT NOT NULL,
    status TEXT,
    gap_description TEXT,
    deadline DATE,
    notes TEXT,
    confidence TEXT NOT NULL DEFAULT 'EMERGING' CHECK (confidence IN ('EMERGING', 'LIKELY', 'CONFIRMED')),
    discovered_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS salesos_legislative (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    account_id UUID REFERENCES salesos_accounts(id),
    finding_id UUID REFERENCES salesos_findings(id),
    title TEXT NOT NULL,
    jurisdiction TEXT NOT NULL,
    bill_number TEXT,
    status TEXT,
    impact_description TEXT,
    effective_date DATE,
    notes TEXT,
    confidence TEXT NOT NULL DEFAULT 'EMERGING' CHECK (confidence IN ('EMERGING', 'LIKELY', 'CONFIRMED')),
    discovered_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS salesos_broadband_projects (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    account_id UUID REFERENCES salesos_accounts(id),
    finding_id UUID REFERENCES salesos_findings(id),
    name TEXT NOT NULL,
    program TEXT,
    status TEXT,
    amount DECIMAL(14,2),
    timeline TEXT,
    notes TEXT,
    confidence TEXT NOT NULL DEFAULT 'EMERGING' CHECK (confidence IN ('EMERGING', 'LIKELY', 'CONFIRMED')),
    discovered_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS salesos_meetings (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    account_id UUID REFERENCES salesos_accounts(id),
    meeting_date DATE NOT NULL,
    attendees JSONB DEFAULT '[]',
    purpose TEXT,
    notes TEXT,
    meddpicc_gaps_addressed JSONB DEFAULT '[]',
    created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS salesos_meddpicc_element_scores (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    account_id UUID REFERENCES salesos_accounts(id),
    snapshot_id UUID REFERENCES salesos_meddpicc_scores(id),
    element TEXT NOT NULL CHECK (element IN ('M', 'E', 'D1', 'D2', 'P1', 'I', 'C1', 'C2')),
    score INT NOT NULL DEFAULT 0 CHECK (score >= 0 AND score <= 3),
    status TEXT NOT NULL DEFAULT 'unknown',
    evidence_summary TEXT DEFAULT '',
    evidence_finding_ids JSONB DEFAULT '[]',
    gap_action TEXT,
    discovery_question TEXT,
    created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS salesos_stage_progress (
    account_id UUID PRIMARY KEY REFERENCES salesos_accounts(id),
    current_stage INT NOT NULL DEFAULT 0,
    stage_entered_at TIMESTAMPTZ DEFAULT now(),
    required_fields JSONB DEFAULT '[]',
    suggested_fields JSONB DEFAULT '[]',
    fields_completed JSONB DEFAULT '{}',
    last_activity TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS salesos_discovery_questions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    account_id UUID REFERENCES salesos_accounts(id),
    question_text TEXT NOT NULL,
    why_needed TEXT NOT NULL,
    target_field TEXT NOT NULL,
    priority TEXT NOT NULL DEFAULT 'SUGGESTED' CHECK (priority IN ('CRITICAL', 'HIGH', 'SUGGESTED')),
    stage_relevant INT NOT NULL,
    status TEXT NOT NULL DEFAULT 'OPEN' CHECK (status IN ('OPEN', 'ANSWERED', 'SKIPPED')),
    answer TEXT,
    answered_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ DEFAULT now()
);

-- SalesOS indexes
CREATE INDEX IF NOT EXISTS idx_token_usage_agent ON token_usage(agent_id);
CREATE INDEX IF NOT EXISTS idx_token_usage_created ON token_usage(created_at);
CREATE INDEX IF NOT EXISTS idx_deal_forecasts_deal_id ON deal_forecasts(deal_id);
CREATE INDEX IF NOT EXISTS idx_deal_forecasts_created ON deal_forecasts(created_at);
CREATE INDEX IF NOT EXISTS idx_proposals_account ON proposals(account_name);
CREATE INDEX IF NOT EXISTS idx_slack_channels_enabled ON slack_channels(enabled);
CREATE INDEX IF NOT EXISTS idx_slack_notifications_created ON slack_notifications(created_at);

-- SalesOS 4.x indexes
CREATE INDEX IF NOT EXISTS idx_salesos_findings_account ON salesos_findings(account_id);
CREATE INDEX IF NOT EXISTS idx_salesos_findings_domain ON salesos_findings(domain);
CREATE INDEX IF NOT EXISTS idx_salesos_findings_status ON salesos_findings(status);
CREATE INDEX IF NOT EXISTS idx_salesos_vendor_stack_account ON salesos_vendor_stack(account_id);
CREATE INDEX IF NOT EXISTS idx_salesos_vendor_stack_layer ON salesos_vendor_stack(layer);
CREATE INDEX IF NOT EXISTS idx_salesos_funding_account ON salesos_funding_sources(account_id);
CREATE INDEX IF NOT EXISTS idx_salesos_procurement_account ON salesos_procurement_history(account_id);
CREATE INDEX IF NOT EXISTS idx_salesos_compliance_account ON salesos_compliance(account_id);
CREATE INDEX IF NOT EXISTS idx_salesos_compliance_framework ON salesos_compliance(framework);
CREATE INDEX IF NOT EXISTS idx_salesos_legislative_account ON salesos_legislative(account_id);
CREATE INDEX IF NOT EXISTS idx_salesos_legislative_jurisdiction ON salesos_legislative(jurisdiction);
CREATE INDEX IF NOT EXISTS idx_salesos_broadband_account ON salesos_broadband_projects(account_id);
CREATE INDEX IF NOT EXISTS idx_salesos_meetings_account ON salesos_meetings(account_id);
CREATE INDEX IF NOT EXISTS idx_salesos_meetings_date ON salesos_meetings(meeting_date);
CREATE INDEX IF NOT EXISTS idx_salesos_meddpicc_elements_account ON salesos_meddpicc_element_scores(account_id);
CREATE INDEX IF NOT EXISTS idx_salesos_discovery_account ON salesos_discovery_questions(account_id);
CREATE INDEX IF NOT EXISTS idx_salesos_discovery_status ON salesos_discovery_questions(status);
"""


def get_sqlite_ddl() -> str:
    return SQLITE_DDL


def get_crdb_ddl() -> str:
    return CRDB_DDL
