#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 16 17:08:43 2025

@author: samd
"""

import sqlite3
from datetime import datetime

def create_database(columns_dict, db_name='articles.db', table_name='articles'):
    """
    Create a SQLite database with a table containing the specified columns.
    
    Args:
        columns_dict: Dictionary mapping column names to SQL data types
                     Example: {'text_en': 'TEXT', 'title_en': 'TEXT', 'date': 'DATE', ...}
        db_name: Name of the database file (default: 'articles.db')
        table_name: Name of the table (default: 'articles')
    """
    # Connect to SQLite database (creates file if it doesn't exist)
    conn = sqlite3.connect(db_name)
    cursor = conn.cursor()
    
    # Build column definitions from dictionary
    column_definitions = ['id INTEGER PRIMARY KEY AUTOINCREMENT']
    for col_name, col_type in columns_dict.items():
        if col_name == 'inserted_at' and col_type.upper() == 'TIMESTAMP':
            column_definitions.append(f'{col_name} {col_type} DEFAULT CURRENT_TIMESTAMP')
        else:
            column_definitions.append(f'{col_name} {col_type}')
    
    # Create the SQL statement
    columns_sql = ',\n            '.join(column_definitions)
    create_table_sql = f'''
        CREATE TABLE IF NOT EXISTS {table_name} (
            {columns_sql}
        )
    '''
    
    # Execute the create table statement
    cursor.execute(create_table_sql)
    
    # Commit changes and close connection
    conn.commit()
    print(f"Database '{db_name}' created successfully!")
    print(f"Table '{table_name}' created with columns: id, {', '.join(columns_dict.keys())}")
    
    conn.close()

def insert_sample_data(db_name='articles.db'):
    """
    Insert sample data into the database.
    """
    conn = sqlite3.connect(db_name)
    cursor = conn.cursor()
    
    # Sample data
    sample_articles = [
        (
            "This is a sample article text in English.",
            "Sample Article Title",
            "2024-01-15",
            datetime.now(),
            "John Doe",
            "Example News"
        ),
        (
            "Another article with different content.",
            "Second Article",
            "2024-02-20",
            datetime.now(),
            "Jane Smith",
            "Tech Blog"
        )
    ]
    
    cursor.executemany('''
        INSERT INTO articles (text_en, title_en, date, inserted_at, author, source)
        VALUES (?, ?, ?, ?, ?, ?)
    ''', sample_articles)
    
    conn.commit()
    print(f"\nInserted {len(sample_articles)} sample records.")
    
    conn.close()

def view_data(db_name='articles.db'):
    """
    View all data in the database.
    """
    conn = sqlite3.connect(db_name)
    cursor = conn.cursor()
    
    cursor.execute('SELECT * FROM articles')
    rows = cursor.fetchall()
    
    print("\n--- Database Contents ---")
    for row in rows:
        print(row)
    
    conn.close()

def view_columns(db_name='articles.db', table_name='articles'):
    """
    View the column names and types of a table in the database.
    
    Args:
        db_name: Name of the database file
        table_name: Name of the table
    """
    conn = sqlite3.connect(db_name)
    cursor = conn.cursor()
    
    # Get table information using PRAGMA
    cursor.execute(f"PRAGMA table_info({table_name})")
    columns = cursor.fetchall()
    
    print(f"\nColumns in table '{table_name}':")
    print("-" * 60)
    print(f"{'Column Name':<20} {'Type':<15} {'Not Null':<10} {'Default'}")
    print("-" * 60)
    
    for column in columns:
        cid, name, col_type, not_null, default_val, pk = column
        print(f"{name:<20} {col_type:<15} {bool(not_null):<10} {default_val}")
    
    conn.close()
    
def insert_data(data_dict, db_name='articles.db', table_name='articles'):
    """
    Insert data into the database.
    
    Args:
        data_dict: Dictionary mapping column names to values
                   Example: {'text_en': 'Article text', 'title_en': 'Title', 'date': '2024-01-15', ...}
        db_name: Name of the database file (default: 'articles.db')
        table_name: Name of the table (default: 'articles')
    """
    conn = sqlite3.connect(db_name)
    cursor = conn.cursor()
    
    # Build the INSERT statement from the dictionary
    columns = ', '.join(data_dict.keys())
    placeholders = ', '.join(['?' for _ in data_dict])
    values = tuple(data_dict.values())
    
    insert_sql = f'''
        INSERT INTO {table_name} ({columns})
        VALUES ({placeholders})
    '''
    
    cursor.execute(insert_sql, values)
    conn.commit()
    
    print(f"Data inserted successfully into '{table_name}' table.")
    print(f"Inserted row ID: {cursor.lastrowid}")
    
    conn.close()
    return cursor.lastrowid

def insert_multiple_data(data_list, db_name='articles.db', table_name='articles'):
    """
    Insert multiple rows of data into the database.
    
    Args:
        data_list: List of dictionaries, where each dictionary represents one row
                   Example: [
                       {'text_en': 'Text 1', 'title_en': 'Title 1', ...},
                       {'text_en': 'Text 2', 'title_en': 'Title 2', ...}
                   ]
        db_name: Name of the database file (default: 'articles.db')
        table_name: Name of the table (default: 'articles')
    """
    if not data_list:
        print("No data to insert.")
        return []
    
    conn = sqlite3.connect(db_name)
    cursor = conn.cursor()
    
    # Get column names from the first dictionary (assuming all dicts have same keys)
    columns = ', '.join(data_list[0].keys())
    placeholders = ', '.join(['?' for _ in data_list[0]])
    
    # Convert list of dicts to list of tuples
    values_list = [tuple(data.values()) for data in data_list]
    
    insert_sql = f'''
        INSERT INTO {table_name} ({columns})
        VALUES ({placeholders})
    '''
    
    cursor.executemany(insert_sql, values_list)
    conn.commit()
    
    print(f"Successfully inserted {len(data_list)} rows into '{table_name}' table.")
    
    conn.close()
    return len(data_list)