import sqlite3
import functools
import os
from pathlib import Path
import json


_is_initialized = False


DB_DIR = str(Path.home() / ".config" / "mana" / "data")
DB_PATH = os.path.join(DB_DIR, "fatigue.db")
CONFIG_PATH = os.path.join(DB_DIR, "config.json")


def _init_db():
    global _is_initialized

    if _is_initialized:
        return
    conn = get_conn()
    cursor = conn.cursor()
    cursor.executescript(
        """
        CREATE TABLE IF NOT EXISTS records (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            start INTEGER,
            stop INTEGER,
            duration INTEGER,   
            task_desc TEXT,
            extra_id TEXT,
            project_id INTEGER
        );
        
        CREATE TABLE IF NOT EXISTS projects (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            project_name TEXT UNIQUE,
            fatigue_rate REAL DEFAULT 1.0,
            fatigue_total INTEGER DEFAULT 156,
            project_status INTEGER DEFAULT 0
        );
    """
    )

    conn.commit()
    conn.close()
    _is_initialized = True


def _create_config():
    if os.path.exists(CONFIG_PATH):
        return
    else:
        with open(CONFIG_PATH, "w", encoding="utf-8") as f:
            default_config = {"enable_timew": True}
            json.dump(default_config, f, indent=4)


def get_conn():
    if not os.path.exists(DB_DIR):
        os.makedirs(DB_DIR, exist_ok=True)

    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    return conn


def ensure_db_ready(func):
    @functools.wraps(func)
    def wrapper(*args, **kargs):
        _init_db()
        _create_config()
        return func(*args, **kargs)

    return wrapper
