"""
Branch license entitlements (tied to main LicenseKey).

Run: python migrations/add_branch_licenses_table.py
"""
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))

from sqlalchemy import text
from app.core.database import engine
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def table_exists(conn, table: str) -> bool:
    bind = engine.url.drivername
    if "sqlite" in bind:
        rows = conn.execute(
            text("SELECT name FROM sqlite_master WHERE type='table' AND name=:t"),
            {"t": table},
        ).fetchall()
        return bool(rows)
    result = conn.execute(
        text(
            "SELECT 1 FROM information_schema.tables WHERE table_name = :t"
        ),
        {"t": table},
    )
    return result.fetchone() is not None


def run_migration():
    with engine.begin() as conn:
        if table_exists(conn, "branch_licenses"):
            logger.info("branch_licenses already exists — skipping")
            return
        logger.info("Creating branch_licenses table…")
        conn.execute(text("""
            CREATE TABLE branch_licenses (
                id VARCHAR(36) PRIMARY KEY,
                parent_license_id VARCHAR(36) NOT NULL REFERENCES license_keys(id),
                company_id VARCHAR(36) NOT NULL REFERENCES companies(id),
                branch_id VARCHAR(36) REFERENCES branches(id),
                slot_code VARCHAR(32) NOT NULL,
                label VARCHAR(255),
                status VARCHAR(20) DEFAULT 'active',
                valid_from TIMESTAMP NOT NULL,
                valid_until TIMESTAMP NOT NULL,
                notes TEXT,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        """))
        conn.execute(text(
            "CREATE INDEX ix_branch_licenses_parent ON branch_licenses (parent_license_id)"
        ))
        conn.execute(text(
            "CREATE INDEX ix_branch_licenses_company ON branch_licenses (company_id)"
        ))
        conn.execute(text(
            "CREATE INDEX ix_branch_licenses_status ON branch_licenses (status)"
        ))
        logger.info("Done.")


if __name__ == "__main__":
    run_migration()
