from __future__ import annotations
import subprocess
from dataclasses import dataclass
from pathlib import Path
from typing import Optional

@dataclass(frozen=True)
class HomebrewMySQLInfo:
    """
    [AI_DOC]
    macOS uzerinde calisan yerel Homebrew MySQL sunucusunun bilgilerini tutar.
    available: Sunucu kurulu ve calisiyor mu?
    socket_path: DB'ye baglanmak icin gereken unix soket yolu.
    [/AI_DOC]
    """
    available: bool
    brew_executable: Optional[str] = None
    mysql_prefix: Optional[str] = None
    var_mysql_dir: Optional[str] = None
    cellar_mysql_dir: Optional[str] = None
    socket_path: Optional[str] = None

    def detected_path_for_log(self) -> str:
        for p in (self.mysql_prefix, self.var_mysql_dir, self.cellar_mysql_dir, self.socket_path, self.brew_executable):
            if p:
                return p
        return "unknown"

def _path_exists(path: str) -> bool:
    try:
        return Path(path).exists()
    except Exception:
        return False

def _run_brew_prefix(brew_cmd: str, timeout_seconds: float = 2.0) -> Optional[str]:
    try:
        cp = subprocess.run(
            [brew_cmd, "--prefix", "mysql"],
            capture_output=True,
            text=True,
            timeout=timeout_seconds,
            check=False,
        )
    except Exception:
        return None
    
    if cp.returncode != 0:
        return None
        
    prefix = (cp.stdout or "").strip()
    if not prefix:
        return None
        
    return prefix

def detect_homebrew_mysql() -> HomebrewMySQLInfo:
    """
    [AI_DOC]
    macOS ortaminda MySQL kurulumunu otomatik algilar. 
    Asagidaki sirayla arama yapar:
      A) `brew --prefix mysql` komutu (yaygin brew yollari denenir)
      B) Homebrew MySQL data/Cellar klasorleri manuel kontrolu
      C) Yaygin MySQL soket yollari
    [/AI_DOC]
    """
    brew_candidates = [
        "/opt/homebrew/bin/brew",
        "/usr/local/bin/brew",
        "brew",
    ]

    for brew_cmd in brew_candidates:
        if brew_cmd != "brew" and not _path_exists(brew_cmd):
            continue
            
        prefix = _run_brew_prefix(brew_cmd)
        if prefix and _path_exists(prefix):
            return HomebrewMySQLInfo(available=True, brew_executable=brew_cmd, mysql_prefix=prefix)

    var_dirs = [
        "/opt/homebrew/var/mysql",
        "/usr/local/var/mysql",
    ]
    for d in var_dirs:
        if _path_exists(d):
            return HomebrewMySQLInfo(available=True, var_mysql_dir=d)

    cellar_dirs = [
        "/opt/homebrew/Cellar/mysql",
        "/usr/local/Cellar/mysql",
    ]
    for d in cellar_dirs:
        if _path_exists(d):
            return HomebrewMySQLInfo(available=True, cellar_mysql_dir=d)

    socket_candidates = [
        "/tmp/mysql.sock",
        "/opt/homebrew/var/mysql/mysql.sock",
        "/usr/local/var/mysql/mysql.sock",
    ]
    for sock in socket_candidates:
        if _path_exists(sock):
            return HomebrewMySQLInfo(available=True, socket_path=sock)

    return HomebrewMySQLInfo(available=False)

def is_homebrew_mysql_available() -> bool:
    return detect_homebrew_mysql().available




