#!/usr/bin/env python3
"""
GHL Domination PRD Executor
===========================
Executes the GHL-DOM-001 PRD via Genesis Execution Layer.
Uses Gemini RWL swarm for maximum velocity.

Usage:
    python loop/run_ghl_domination.py [--story STORY_ID] [--phase PHASE_NUM]
"""

import os
import sys
import json
import asyncio
import argparse
from pathlib import Path
from datetime import datetime

# Add genesis-system to path
sys.path.insert(0, str(Path(__file__).parent.parent))

from core.genesis_execution_layer import execute_task_sync, GenesisExecutionLayer

PRD_PATH = Path(__file__).parent / "GHL_DOMINATION_MASTERY_PRD.json"
REPORT_PATH = Path(__file__).parent / "GHL_DOMINATION_REPORT.md"


def load_prd():
    """Load the PRD JSON file."""
    with open(PRD_PATH, 'r') as f:
        return json.load(f)


def generate_story_prompt(story: dict) -> str:
    """Generate execution prompt for a story."""
    prompt = f"""
## Task: {story['title']}

### Story ID: {story['id']}

### Description
{story['description']}

### Acceptance Criteria
{chr(10).join(f"- {ac}" for ac in story['acceptance_criteria'])}

### Test Plan
**Black Box Tests:**
{chr(10).join(f"- {t}" for t in story['test_plan']['black_box'])}

**White Box Tests:**
{chr(10).join(f"- {t}" for t in story['test_plan']['white_box'])}

### Output Requirements
1. Create all entity files in KNOWLEDGE_GRAPH/entities/ghl/
2. Use JSON format with consistent schema
3. Include all required fields from acceptance criteria
4. Create test verification file

### File Structure
- Entity files: KNOWLEDGE_GRAPH/entities/ghl/{story['id'].lower()}_*.json
- Test file: skills/ghl/tests/test_{story['id'].lower()}.py

Execute this story completely. Return DONE when all acceptance criteria are met.
"""
    return prompt


def execute_story(story: dict) -> dict:
    """Execute a single story via Genesis Execution Layer."""
    print(f"\n{'='*60}")
    print(f"Executing: {story['id']} - {story['title']}")
    print(f"{'='*60}")

    prompt = generate_story_prompt(story)

    try:
        result = execute_task_sync(prompt)
        return {
            "story_id": story['id'],
            "status": "success" if result else "failed",
            "result": result,
            "timestamp": datetime.now().isoformat()
        }
    except Exception as e:
        return {
            "story_id": story['id'],
            "status": "error",
            "error": str(e),
            "timestamp": datetime.now().isoformat()
        }


def execute_phase(prd: dict, phase_num: int) -> list:
    """Execute all stories in a phase."""
    phase_ranges = {
        1: (0, 3),   # Stories 1-3
        2: (3, 8),   # Stories 4-8
        3: (8, 11),  # Stories 9-11
        4: (11, 18), # Stories 12-18
        5: (18, 20)  # Stories 19-20
    }

    start, end = phase_ranges.get(phase_num, (0, len(prd['stories'])))
    stories = prd['stories'][start:end]

    results = []
    for story in stories:
        result = execute_story(story)
        results.append(result)

        if result['status'] == 'error':
            print(f"⚠️ Story {story['id']} failed: {result.get('error')}")
        else:
            print(f"✅ Story {story['id']} completed")

    return results


def generate_report(prd: dict, results: list):
    """Generate execution report."""
    success_count = sum(1 for r in results if r['status'] == 'success')
    total = len(results)

    report = f"""# GHL Domination Execution Report
**Generated**: {datetime.now().isoformat()}
**PRD**: GHL-DOM-001

## Summary
| Metric | Value |
|--------|-------|
| Stories Executed | {total} |
| Successful | {success_count} |
| Failed | {total - success_count} |
| Success Rate | {(success_count/total*100):.1f}% |

## Results

"""

    for result in results:
        status_icon = "✅" if result['status'] == 'success' else "❌"
        report += f"### {status_icon} {result['story_id']}\n"
        report += f"- Status: {result['status']}\n"
        report += f"- Timestamp: {result['timestamp']}\n"
        if result.get('error'):
            report += f"- Error: {result['error']}\n"
        report += "\n"

    with open(REPORT_PATH, 'w') as f:
        f.write(report)

    print(f"\n📄 Report written to: {REPORT_PATH}")
    return report


def main():
    parser = argparse.ArgumentParser(description='Execute GHL Domination PRD')
    parser.add_argument('--story', type=str, help='Execute specific story (e.g., GHL-001)')
    parser.add_argument('--phase', type=int, help='Execute specific phase (1-5)')
    parser.add_argument('--all', action='store_true', help='Execute all stories')
    args = parser.parse_args()

    prd = load_prd()
    print(f"📋 Loaded PRD: {prd['title']}")
    print(f"📊 Total Stories: {len(prd['stories'])}")

    results = []

    if args.story:
        # Execute single story
        story = next((s for s in prd['stories'] if s['id'] == args.story), None)
        if story:
            results = [execute_story(story)]
        else:
            print(f"❌ Story {args.story} not found")
            return
    elif args.phase:
        # Execute phase
        results = execute_phase(prd, args.phase)
    elif args.all:
        # Execute all
        for story in prd['stories']:
            results.append(execute_story(story))
    else:
        # Default: show status
        print("\nUsage:")
        print("  --story GHL-001  Execute specific story")
        print("  --phase 1        Execute phase 1 (stories 1-3)")
        print("  --all            Execute all stories")
        return

    generate_report(prd, results)


if __name__ == "__main__":
    main()
