"""
Progress Dashboard API
======================
Generated by El Gringo team (chatgpt-coder, grok-coder, gemini-creative).
Fixed: Goal dataclass field order, correct import names, method alignment
with sprint_manager and standup modules.
"""

import json
import threading
import uuid
from dataclasses import asdict, dataclass, field
from datetime import datetime, timedelta
from pathlib import Path
from typing import Dict, List

from flask import Blueprint, jsonify, request

from .sprint_manager import SprintManager
from .standup import StandupGenerator

progress_bp = Blueprint("progress", __name__, url_prefix="/api/progress")

GOALS_FILE = Path.home() / ".ai-dev-team" / "workflow" / "goals.json"
GOALS_FILE.parent.mkdir(parents=True, exist_ok=True)

_lock = threading.Lock()


@dataclass
class Goal:
    title: str = ""
    description: str = ""
    deadline: str = ""
    project: str = ""
    id: str = field(default_factory=lambda: str(uuid.uuid4())[:8])
    is_completed: bool = False
    created_at: str = field(default_factory=lambda: datetime.now().isoformat())


def _load_goals() -> List[Dict]:
    with _lock:
        if GOALS_FILE.exists():
            with GOALS_FILE.open("r") as f:
                return json.load(f)
    return []


def _save_goals(goals: List[Dict]):
    with _lock:
        with GOALS_FILE.open("w") as f:
            json.dump(goals, f, indent=2)


@progress_bp.route("/summary", methods=["GET"])
def get_summary():
    try:
        sm = SprintManager()
        return jsonify(sm.get_summary_stats())
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@progress_bp.route("/sprint", methods=["GET"])
def get_sprint():
    try:
        sm = SprintManager()
        sprint = sm.get_current_sprint()
        if not sprint:
            return jsonify({"error": "No active sprint"}), 404
        tasks = sm.get_tasks_for_sprint(sprint.id)
        return jsonify({
            "sprint": asdict(sprint),
            "tasks": [asdict(t) for t in tasks],
            "completion_percentage": sm.calculate_sprint_completion(sprint.id),
        })
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@progress_bp.route("/standup", methods=["GET"])
def get_standup():
    try:
        sg = StandupGenerator()
        data = sg.generate_standup()
        return jsonify({
            "date": data["date"],
            "formatted": sg.format_standup(data),
            "raw": data,
        })
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@progress_bp.route("/weekly", methods=["GET"])
def get_weekly():
    try:
        sm = SprintManager()
        week_ago = (datetime.now() - timedelta(days=7)).isoformat()
        completed = sm.get_tasks_completed_since(week_ago)
        goals = _load_goals()
        return jsonify({
            "tasks_completed": len(completed),
            "completed_titles": [t.title for t in completed],
            "velocity_trend": sm.get_velocity_trend(weeks=4),
            "goals": goals,
        })
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@progress_bp.route("/goal", methods=["POST"])
def create_goal():
    data = request.get_json(silent=True) or {}
    for f in ("title", "deadline"):
        if f not in data:
            return jsonify({"error": f"Missing required field: {f}"}), 400
    goal = Goal(
        title=data["title"],
        description=data.get("description", ""),
        deadline=data["deadline"],
        project=data.get("project", ""),
    )
    goals = _load_goals()
    goals.append(asdict(goal))
    _save_goals(goals)
    return jsonify(asdict(goal)), 201


@progress_bp.route("/goals", methods=["GET"])
def list_goals():
    return jsonify(_load_goals())
