"""
Daily Standup Generator
=======================
Generated by El Gringo team (grok-reasoner, chatgpt-coder, gemini-creative).
Fixed: removed markdown fences, wired into sprint_manager for real task data.
"""

import json
import subprocess
from datetime import datetime, timedelta
from pathlib import Path
from typing import Dict, List, Optional


class StandupGenerator:
    def __init__(self):
        self.standup_dir = Path.home() / ".ai-dev-team" / "workflow" / "standups"
        self.standup_dir.mkdir(parents=True, exist_ok=True)
        self.default_project_dir = Path.home() / "Development" / "Projects"

    def get_git_activity(self, repo_path: Path, hours: int = 24) -> List[str]:
        since = (datetime.now() - timedelta(hours=hours)).strftime("%Y-%m-%dT%H:%M:%S")
        try:
            result = subprocess.run(
                ["git", "-C", str(repo_path), "log", "--since", since,
                 "--pretty=format:%h %s (%an)", "--no-merges"],
                capture_output=True, text=True, timeout=10,
            )
            if result.returncode == 0 and result.stdout.strip():
                return result.stdout.strip().split("\n")
        except (subprocess.SubprocessError, FileNotFoundError):
            pass
        return []

    def get_task_changes(self) -> Dict[str, List[str]]:
        try:
            from .sprint_manager import SprintManager
            sm = SprintManager()
            yesterday = (datetime.now() - timedelta(hours=24)).isoformat()
            completed = [t.title for t in sm.tasks
                         if t.status == "done" and t.updated_at >= yesterday]
            in_progress = [t.title for t in sm.tasks if t.status == "in_progress"]
            blocked = [t.title for t in sm.tasks if t.status == "review"]
            return {"completed": completed, "in_progress": in_progress, "blocked": blocked}
        except Exception:
            return {"completed": [], "in_progress": [], "blocked": []}

    def _is_git_repo(self, path: Path) -> bool:
        try:
            return path.is_dir() and (path / ".git").is_dir()
        except (OSError, TimeoutError):
            return False

    def generate_standup(self, repos: Optional[List[Path]] = None) -> Dict:
        if repos is None:
            repos = [d for d in self.default_project_dir.iterdir() if self._is_git_repo(d)]
        standup_data = {
            "date": datetime.now().strftime("%Y-%m-%d"),
            "generated_at": datetime.now().isoformat(),
            "repos": {},
            "tasks": self.get_task_changes(),
        }
        for repo in repos:
            commits = self.get_git_activity(repo)
            if commits:
                standup_data["repos"][repo.name] = commits
        return standup_data

    def format_standup(self, standup_data: Dict) -> str:
        date = standup_data["date"]
        lines = [f"Daily Standup — {date}", "=" * 35, ""]

        lines.append("Yesterday:")
        if standup_data["repos"]:
            for repo, commits in standup_data["repos"].items():
                lines.append(f"  [{repo}]")
                for c in commits[:10]:
                    lines.append(f"    - {c}")
        tasks = standup_data["tasks"]
        if tasks["completed"]:
            lines.append("  [Tasks completed]")
            for t in tasks["completed"]:
                lines.append(f"    - {t}")
        if not standup_data["repos"] and not tasks["completed"]:
            lines.append("  No activity in the last 24 hours.")

        lines.append("")
        lines.append("Today:")
        if tasks["in_progress"]:
            for t in tasks["in_progress"]:
                lines.append(f"  - {t}")
        else:
            lines.append("  No tasks in progress.")

        lines.append("")
        lines.append("Blockers:")
        if tasks["blocked"]:
            for t in tasks["blocked"]:
                lines.append(f"  - {t}")
        else:
            lines.append("  None")

        return "\n".join(lines)

    def save_standup(self, standup_data: Dict) -> Path:
        filepath = self.standup_dir / f"{standup_data['date']}.json"
        with filepath.open("w") as f:
            json.dump(standup_data, f, indent=2)
        return filepath

    def get_standup_history(self, days: int = 7) -> List[Dict]:
        cutoff = datetime.now() - timedelta(days=days)
        history = []
        for fp in sorted(self.standup_dir.glob("*.json"), reverse=True):
            try:
                date = datetime.strptime(fp.stem, "%Y-%m-%d")
                if date >= cutoff:
                    with fp.open("r") as f:
                        history.append(json.load(f))
            except (ValueError, json.JSONDecodeError):
                continue
        return history
