import os
import re
import json
import streamlit as st
from bs4 import BeautifulSoup

# Konštanty a Cesty
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.join(BASE_DIR, "data")
MODELS_DIR = os.path.join(DATA_DIR, "models")
INPUTS_DIR = os.path.join(DATA_DIR, "inputs")
RUNS_DIR = os.path.join(DATA_DIR, "runs")
PROMPTS_DIR = os.path.join(DATA_DIR, "prompts")
BASE_PROMPT_FILE = os.path.join(PROMPTS_DIR, "base_prompt.txt")
MODEL_CAPABILITIES_FILE = os.path.join(DATA_DIR, "model_capabilities.json")


def init_directories():
    for directory in [DATA_DIR, MODELS_DIR, INPUTS_DIR, RUNS_DIR, PROMPTS_DIR]:
        if not os.path.exists(directory):
            os.makedirs(directory)


def get_files_in_dir(directory):
    return [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]


def get_folders_in_dir(directory):
    return [d for d in os.listdir(directory) if os.path.isdir(os.path.join(directory, d))]


def clean_html(raw_html: str) -> str:
    """Strip scripts, styles, and other non-content tags from HTML, returning cleaned HTML."""
    soup = BeautifulSoup(raw_html, "html.parser")

    for tag in soup.find_all(["script", "style", "noscript", "iframe",
                               "svg", "canvas", "video", "audio", "template"]):
        tag.decompose()

    noise_attrs = re.compile(r"^(on\w+|style|class|id|data-[\w-]+)$", re.IGNORECASE)
    for tag in soup.find_all(True):
        for attr in list(tag.attrs):
            if noise_attrs.match(attr):
                del tag.attrs[attr]

    cleaned = str(soup)
    cleaned = re.sub(r"\n{3,}", "\n\n", cleaned)
    return cleaned


def save_uploaded_file(uploaded_file, target_dir):
    try:
        with open(os.path.join(target_dir, uploaded_file.name), "wb") as f:
            f.write(uploaded_file.getbuffer())
        return True
    except Exception as e:
        from VerifierApp.localisation_module import t
        st.error(t("config_save_error", name=uploaded_file.name, error=e))
        return False


def get_base_prompt():
    if not os.path.exists(BASE_PROMPT_FILE):
        default_text = (
            "Ste expert na systémovú biológiu. Vašou úlohou je extrahovať fenotypy...\n"
            "DÔLEŽITÉ PRAVIDLÁ:\n"
            "1. 'stable active' (1), 'stable inactive' (0), 'unstable' (osciluje).\n"
            "2. Používajte VÝHRADNE presné názvy ID z kontextu modelu.\n"
            "3. Identifikujte vstupné premenné (inputs)."
        )
        with open(BASE_PROMPT_FILE, "w", encoding="utf-8") as f:
            f.write(default_text)
        return default_text

    with open(BASE_PROMPT_FILE, "r", encoding="utf-8") as f:
        return f.read()


def save_base_prompt(new_prompt_text):
    with open(BASE_PROMPT_FILE, "w", encoding="utf-8") as f:
        f.write(new_prompt_text)


def load_model_capability_overrides() -> dict:
    """Load per-model capability overrides from disk.

    Returns a dict like ``{"qwen3.5-122b": {"pdf": "extract"}, ...}``.
    ``"pdf"`` values are ``"auto"`` | ``"extract"`` | ``"native"``.
    Returns ``{}`` if no file exists yet.
    """
    if not os.path.exists(MODEL_CAPABILITIES_FILE):
        return {}
    try:
        with open(MODEL_CAPABILITIES_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    except Exception:
        return {}


def save_model_capability_overrides(overrides: dict) -> None:
    """Persist *overrides* to disk, removing any entries set to 'auto'."""
    clean = {
        model_id: caps
        for model_id, caps in overrides.items()
        if caps.get("pdf", "auto") != "auto"
    }
    with open(MODEL_CAPABILITIES_FILE, "w", encoding="utf-8") as f:
        json.dump(clean, f, indent=2, ensure_ascii=False)

