from web.database import query_db, execute_db
import json
from datetime import datetime

class WebService:
    # --- Comments ---
    @staticmethod
    def get_comments(target_type, target_id):
        sql = "SELECT * FROM comments WHERE target_type = ? AND target_id = ? AND is_hidden = 0 ORDER BY created_at DESC"
        return query_db('web', sql, [target_type, target_id])

    @staticmethod
    def add_comment(user_id, username, target_type, target_id, content):
        sql = """
            INSERT INTO comments (user_id, username, target_type, target_id, content)
            VALUES (?, ?, ?, ?, ?)
        """
        return execute_db('web', sql, [user_id, username, target_type, target_id, content])

    @staticmethod
    def like_comment(comment_id):
        sql = "UPDATE comments SET likes = likes + 1 WHERE id = ?"
        return execute_db('web', sql, [comment_id])

    # --- Wiki ---
    @staticmethod
    def get_wiki_page(path):
        sql = "SELECT * FROM wiki_pages WHERE path = ?"
        return query_db('web', sql, [path], one=True)
    
    @staticmethod
    def get_all_wiki_pages():
        sql = "SELECT path, title FROM wiki_pages ORDER BY path"
        return query_db('web', sql)

    @staticmethod
    def save_wiki_page(path, title, content, updated_by):
        # Upsert logic
        check = query_db('web', "SELECT id FROM wiki_pages WHERE path = ?", [path], one=True)
        if check:
            sql = "UPDATE wiki_pages SET title=?, content=?, updated_by=?, updated_at=CURRENT_TIMESTAMP WHERE path=?"
            execute_db('web', sql, [title, content, updated_by, path])
        else:
            sql = "INSERT INTO wiki_pages (path, title, content, updated_by) VALUES (?, ?, ?, ?)"
            execute_db('web', sql, [path, title, content, updated_by])

    # --- Team Lineups ---
    @staticmethod
    def save_lineup(name, description, player_ids, lineup_id=None):
        # player_ids is a list
        ids_json = json.dumps(player_ids)
        if lineup_id:
            sql = "UPDATE team_lineups SET name=?, description=?, player_ids_json=? WHERE id=?"
            return execute_db('web', sql, [name, description, ids_json, lineup_id])
        else:
            sql = "INSERT INTO team_lineups (name, description, player_ids_json) VALUES (?, ?, ?)"
            return execute_db('web', sql, [name, description, ids_json])

    @staticmethod
    def get_lineups():
        return query_db('web', "SELECT * FROM team_lineups ORDER BY created_at DESC")

    @staticmethod
    def get_lineup(lineup_id):
        return query_db('web', "SELECT * FROM team_lineups WHERE id = ?", [lineup_id], one=True)


    # --- Users / Auth ---
    @staticmethod
    def get_user_by_token(token):
        sql = "SELECT * FROM users WHERE token = ?"
        return query_db('web', sql, [token], one=True)

    # --- Player Metadata ---
    @staticmethod
    def get_player_metadata(steam_id):
        sql = "SELECT * FROM player_metadata WHERE steam_id_64 = ?"
        row = query_db('web', sql, [steam_id], one=True)
        if row:
            res = dict(row)
            try:
                res['tags'] = json.loads(res['tags']) if res['tags'] else []
            except:
                res['tags'] = []
            return res
        return {'steam_id_64': steam_id, 'notes': '', 'tags': []}

    @staticmethod
    def update_player_metadata(steam_id, notes=None, tags=None):
        # Upsert
        check = query_db('web', "SELECT steam_id_64 FROM player_metadata WHERE steam_id_64 = ?", [steam_id], one=True)
        
        tags_json = json.dumps(tags) if tags is not None else None
        
        if check:
            # Update
            clauses = []
            args = []
            if notes is not None:
                clauses.append("notes = ?")
                args.append(notes)
            if tags is not None:
                clauses.append("tags = ?")
                args.append(tags_json)
            
            if clauses:
                clauses.append("updated_at = CURRENT_TIMESTAMP")
                sql = f"UPDATE player_metadata SET {', '.join(clauses)} WHERE steam_id_64 = ?"
                args.append(steam_id)
                execute_db('web', sql, args)
        else:
            # Insert
            sql = "INSERT INTO player_metadata (steam_id_64, notes, tags) VALUES (?, ?, ?)"
            execute_db('web', sql, [steam_id, notes or '', tags_json or '[]'])
    
    # --- Strategy Board ---
    @staticmethod
    def save_strategy_board(title, map_name, data_json, created_by):
        sql = "INSERT INTO strategy_boards (title, map_name, data_json, created_by) VALUES (?, ?, ?, ?)"
        return execute_db('web', sql, [title, map_name, data_json, created_by])
