#!/usr/bin/env python3
"""
Initialize DSS Demo Database

Creates a fresh database with all migrations applied
and demo data loaded.
"""

import sys
import sqlite3
import hashlib
from pathlib import Path

# Database location
DB_PATH = Path(".dss/dss.db")
DB_PATH.parent.mkdir(parents=True, exist_ok=True)

def init_database():
    """Initialize database with full schema"""
    print(f"Initializing database at {DB_PATH}")

    # Remove existing database
    if DB_PATH.exists():
        DB_PATH.unlink()
        print("Removed existing database")

    # Import and run init
    sys.path.insert(0, str(Path("tools").resolve()))
    from storage.database import init_database as init_db
    init_db()
    print("Base schema created")

    # Apply migrations
    conn = sqlite3.connect(DB_PATH)

    # Migration 003: Integrations
    with open("tools/storage/migrations/003_add_integrations.sql") as f:
        conn.executescript(f.read())
    print("Migration 003 applied (integrations)")

    # Drop old users table if exists
    conn.execute("DROP TABLE IF EXISTS users")

    # Migration 004: Users
    with open("tools/storage/migrations/004_add_users.sql") as f:
        conn.executescript(f.read())
    print("Migration 004 applied (users)")

    # Create demo user
    token_hash = hashlib.sha256("1234".encode()).hexdigest()
    conn.execute('''
        INSERT OR REPLACE INTO users (
            email, display_name, atlassian_url, atlassian_service,
            api_token_hash, created_at, is_admin
        ) VALUES (?, ?, ?, ?, ?, datetime('now'), 1)
    ''', ('admin@dss.local', 'Admin (Mock)', 'https://mock.atlassian.net', 'jira', token_hash))
    print("Demo user created: admin@dss.local (token: 1234)")

    # Create demo project
    conn.execute('''
        INSERT OR REPLACE INTO projects (
            id, name, description, status, created_at
        ) VALUES (?, ?, ?, 'active', datetime('now'))
    ''', ('demo-ds', 'Demo Design System', 'Demo project for testing DSS capabilities'))
    print("Demo project created: demo-ds")

    conn.commit()
    conn.close()

    print(f"\n✓ Database initialized successfully at {DB_PATH}")
    print("  - Base schema: ✓")
    print("  - Integrations: ✓")
    print("  - Users table: ✓")
    print("  - Demo user: admin@dss.local")
    print("  - Demo project: demo-ds")

if __name__ == "__main__":
    init_database()
