import sqlite3
import uuid

def init_db():
    conn = sqlite3.connect('countries.db')
    c = conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS countries
                 (name TEXT PRIMARY KEY)''')
    c.execute('''CREATE TABLE IF NOT EXISTS settings
                 (key TEXT PRIMARY KEY, value TEXT)''')
    c.execute('''CREATE TABLE IF NOT EXISTS shared_maps
                 (id TEXT PRIMARY KEY, countries TEXT, highlight_color TEXT, map_type TEXT)''')
    conn.commit()
    conn.close()

def add_country(country):
    conn = sqlite3.connect('countries.db')
    c = conn.cursor()
    c.execute("INSERT OR IGNORE INTO countries (name) VALUES (?)", (country,))
    conn.commit()
    conn.close()

def remove_country(country):
    conn = sqlite3.connect('countries.db')
    c = conn.cursor()
    c.execute("DELETE FROM countries WHERE name = ?", (country,))
    conn.commit()
    conn.close()

def get_all_countries():
    conn = sqlite3.connect('countries.db')
    c = conn.cursor()
    c.execute("SELECT name FROM countries")
    countries = [row[0] for row in c.fetchall()]
    conn.close()
    return countries

def save_highlight_color(color):
    conn = sqlite3.connect('countries.db')
    c = conn.cursor()
    c.execute("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)", ('highlight_color', color))
    conn.commit()
    conn.close()

def get_highlight_color():
    conn = sqlite3.connect('countries.db')
    c = conn.cursor()
    c.execute("SELECT value FROM settings WHERE key = 'highlight_color'")
    result = c.fetchone()
    conn.close()
    return result[0] if result else None

def save_map_type(map_type):
    conn = sqlite3.connect('countries.db')
    c = conn.cursor()
    c.execute("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)", ('map_type', map_type))
    conn.commit()
    conn.close()

def get_map_type():
    conn = sqlite3.connect('countries.db')
    c = conn.cursor()
    c.execute("SELECT value FROM settings WHERE key = 'map_type'")
    result = c.fetchone()
    conn.close()
    return result[0] if result else 'standard'

def create_shared_map(countries, highlight_color, map_type):
    map_id = str(uuid.uuid4())
    conn = sqlite3.connect('countries.db')
    c = conn.cursor()
    c.execute("INSERT INTO shared_maps (id, countries, highlight_color, map_type) VALUES (?, ?, ?, ?)",
              (map_id, ','.join(countries), highlight_color, map_type))
    conn.commit()
    conn.close()
    return map_id

def get_shared_map(map_id):
    conn = sqlite3.connect('countries.db')
    c = conn.cursor()
    c.execute("SELECT * FROM shared_maps WHERE id = ?", (map_id,))
    result = c.fetchone()
    conn.close()
    if result:
        return {
            'id': result[0],
            'countries': result[1].split(','),
            'highlight_color': result[2],
            'map_type': result[3]
        }
    return None
