import os
import re
import shutil
import subprocess
import sys
from datetime import datetime
from pathlib import Path


def _git_env(gh_token: str | None = None) -> dict[str, str]:
    env = os.environ.copy()
    if gh_token:
        env["GH_TOKEN"] = gh_token
    return env


def get_default_branch(repo_path: Path) -> str:
    """Zjistí výchozí větev repozitáře (např. main nebo master)."""
    res = subprocess.run(["git", "symbolic-ref", "refs/remotes/origin/HEAD"], cwd=repo_path, capture_output=True, text=True)
    if res.returncode == 0:
        return res.stdout.strip().split("/")[-1]
    for b in ("main", "master"):
        check = subprocess.run(["git", "rev-parse", "--verify", b], cwd=repo_path, capture_output=True)
        if check.returncode == 0:
            return b
    return "main"


def get_base_ref(repo_path: Path) -> str:
    """Vrátí referenci na vzdálenou výchozí větev (origin/main) nebo lokální fallback."""
    default_branch = get_default_branch(repo_path)
    base_ref = f"origin/{default_branch}"
    check = subprocess.run(["git", "rev-parse", "--verify", base_ref], cwd=repo_path, capture_output=True)
    if check.returncode == 0:
        return base_ref
    return default_branch


def prepare_branch(
    repo_path: Path,
    task_desc: str,
    author_name: str,
    author_email: str,
    gh_token: str | None = None
) -> str:
    env = _git_env(gh_token)

    # 1. Safe directory pro Git (řeší dubious ownership v Dockeru)
    subprocess.run(["git", "config", "--global", "--add", "safe.directory", "*"], capture_output=True)

    # 2. Odstranění visícího index.lock z předchozích procesů
    lock_file = repo_path / ".git" / "index.lock"
    if lock_file.exists():
        try:
            lock_file.unlink()
        except Exception:
            pass

    # 3. Nastavení identity pro commit
    subprocess.run(["git", "config", "user.name", author_name], cwd=repo_path, check=True)
    subprocess.run(["git", "config", "user.email", author_email], cwd=repo_path, check=True)

    # 4. Nastavení GitHub auth pro Git příkazy (fetch, pull, push)
    if gh_token:
        subprocess.run(["gh", "auth", "setup-git"], cwd=repo_path, env=env, capture_output=True)

    # 5. Uklizení necommitnutých změn z předchozích nedokončených běhů
    subprocess.run(["git", "reset", "--hard", "HEAD"], cwd=repo_path, capture_output=True)
    subprocess.run(["git", "clean", "-fd"], cwd=repo_path, capture_output=True)

    # 6. Fetch z origin s předaným tokenem a podrobnou chybovou hláškou
    fetch_proc = subprocess.run(
        ["git", "fetch", "origin"],
        cwd=repo_path,
        env=env,
        capture_output=True,
        text=True
    )
    if fetch_proc.returncode != 0:
        err = fetch_proc.stderr.strip() or fetch_proc.stdout.strip()
        raise RuntimeError(f"Chyba při `git fetch origin`:\n{err}")

    default_branch = get_default_branch(repo_path)

    # 7. Přepnutí na výchozí větev a synchronizace s origin
    checkout_proc = subprocess.run(
        ["git", "checkout", default_branch],
        cwd=repo_path,
        capture_output=True,
        text=True
    )
    if checkout_proc.returncode != 0:
        err = checkout_proc.stderr.strip() or checkout_proc.stdout.strip()
        raise RuntimeError(f"Chyba při `git checkout {default_branch}`:\n{err}")

    # Reset na aktuální origin výchozí větve pro čistý výchozí stav
    subprocess.run(["git", "reset", "--hard", f"origin/{default_branch}"], cwd=repo_path, env=env, capture_output=True)
    subprocess.run(["git", "clean", "-fd"], cwd=repo_path, capture_output=True)

    # 8. Vytvoření nové pracovní větve pro úkol
    slug = re.sub(r"[^a-z0-9]+", "-", task_desc.lower())[:25].strip("-") or "task"
    branch_name = f"mipilot/{datetime.now().strftime('%m%d-%H%M%S')}-{slug}"
    subprocess.run(["git", "checkout", "-b", branch_name], cwd=repo_path, check=True)
    return branch_name


def has_changes(repo_path: Path) -> bool:
    """Zkontroluje, zda v repozitáři proběhly nějaké změny (necommitnuté soubory NEBO nové commity od agenta)."""
    # 1. Necommitnuté změny v pracovním stromu / indexu (tracked i untracked)
    status = subprocess.run(["git", "status", "--porcelain"], cwd=repo_path, capture_output=True, text=True)
    if status.stdout.strip():
        return True

    # 2. Nové commity na aktuální větvi oproti výchozí větvi (pokud agent sám spustil git commit)
    base_ref = get_base_ref(repo_path)
    revs = subprocess.run(
        ["git", "rev-list", f"{base_ref}..HEAD"],
        cwd=repo_path,
        capture_output=True,
        text=True,
    )
    if revs.returncode == 0 and revs.stdout.strip():
        return True

    return False


def cleanup_branch(repo_path: Path, branch_name: str) -> None:
    """Vrátí repozitář na výchozí větev a smaže dočasnou větev."""
    try:
        default_branch = get_default_branch(repo_path)
        subprocess.run(["git", "checkout", default_branch], cwd=repo_path, capture_output=True)
        subprocess.run(["git", "branch", "-D", branch_name], cwd=repo_path, capture_output=True)
    except Exception:
        pass


def scan_for_secrets(repo_path: Path) -> None:
    """Zkontroluje repozitář na přítomnost tajných klíčů pomocí gitleaks."""
    gitleaks_bin = shutil.which("gitleaks") or "/usr/local/bin/gitleaks"
    if Path(gitleaks_bin).is_file():
        proc = subprocess.run(
            [gitleaks_bin, "dir", str(repo_path)],
            cwd=repo_path,
            capture_output=True,
            text=True,
        )
        if proc.returncode != 0:
            output = proc.stdout.strip() or proc.stderr.strip()
            raise RuntimeError(f"Bezpečnostní blokace! gitleaks našel potenciální únik tajných klíčů:\n{output}")
        return

    print("[git_ops] Varování: Nástroj gitleaks nebyl nalezen v PATH, kontrola sekretů přeskočena.")


def commit_push_and_pr(
    repo_path: Path,
    branch_name: str,
    task_desc: str,
    preview_url: str,
    gh_token: str
) -> str:
    # 1. Ujistíme se, že jsme na správné větvi
    curr_branch = subprocess.run(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=repo_path, capture_output=True, text=True).stdout.strip()
    if curr_branch != branch_name:
        subprocess.run(["git", "checkout", branch_name], cwd=repo_path, check=True)

    status = subprocess.run(["git", "status", "--porcelain"], cwd=repo_path, capture_output=True, text=True)
    base_ref = get_base_ref(repo_path)
    new_commits = subprocess.run(
        ["git", "rev-list", f"{base_ref}..HEAD"],
        cwd=repo_path,
        capture_output=True,
        text=True,
    ).stdout.strip()

    if not status.stdout.strip() and not new_commits:
        raise RuntimeError("Agent neprovedl v repozitáři žádné změny.")

    scan_for_secrets(repo_path)

    # 2. Pokud jsou necommitnuté změny (např. agent soubory jen zapsal, ale necommitnul)
    if status.stdout.strip():
        subprocess.run(["git", "add", "."], cwd=repo_path, check=True)
        subprocess.run(["git", "commit", "-m", f"feat: {task_desc[:60]}"], cwd=repo_path, check=True)

    # 3. Push větve
    env = _git_env(gh_token)
    subprocess.run(["gh", "auth", "setup-git"], cwd=repo_path, env=env, check=True)
    subprocess.run(["git", "push", "-u", "origin", branch_name], cwd=repo_path, env=env, check=True)

    # 4. Vytvoření Pull Requestu
    pr_body = (
        f"### Zadání pro mipilot\n{task_desc}\n\n"
        f"### Živý náhled (Preview)\n🔗 **Otestovat změny:** {preview_url}\n\n"
        f"_Automaticky vygenerováno agentem mipilot._"
    )
    pr_proc = subprocess.run(
        ["gh", "pr", "create", "--title", f"[mipilot] {task_desc[:65]}", "--body", pr_body],
        cwd=repo_path,
        env=env,
        capture_output=True,
        text=True,
        check=True
    )
    return pr_proc.stdout.strip()
