"""
Script to split consolidated templates into 3-phase templates
"""
import re
import os
import sys

os.chdir('/mnt/data-disk1/archie-platform-v3/docs/templates')

def extract_phase_content(content, phase_number):
    """Extract content for a specific phase"""
    phase_pattern = f"# PHASE {phase_number}:.*?(?=# PHASE {phase_number + 1}:|# FINAL DEFINITION OF DONE|$)"
    match = re.search(phase_pattern, content, re.DOTALL)
    return match.group(0) if match else ""

def extract_header(content):
    """Extract the header content before PHASE 1"""
    match = re.search(r"^(.*?)(?=# PHASE 1:)", content, re.DOTALL)
    return match.group(1) if match else ""

def extract_footer(content):
    """Extract footer content (Resources, Labels, Links)"""
    match = re.search(r"(## Resources.*?## Links.*?)```", content, re.DOTALL)
    return match.group(1) if match else ""

def get_title_format(content, category_code):
    """Extract title format from content"""
    title_match = re.search(r"## Title Format\n`\[" + category_code + r"\](.*?)`", content)
    return title_match.group(1) if title_match else " {SERVICE_NAME}..."

def get_purpose(content):
    """Extract purpose from content"""
    purpose_match = re.search(r"## Purpose\n\n(.*?)\n\n\*\*Reference", content, re.DOTALL)
    if purpose_match:
        return purpose_match.group(1).strip()
    return "Implement comprehensive functionality..."

def create_spec_template(category_code, category_name, source_content, spec_secondary):
    """Create SPEC template"""
    header = extract_header(source_content)
    phase1 = extract_phase_content(source_content, 1)
    footer = extract_footer(source_content)
    title_format = get_title_format(source_content, category_code)
    purpose = get_purpose(source_content)

    template = f'''# {category_name} Specification Template

## Title Format
`[{category_code}-SPEC]{title_format}`

---

## Template

```markdown
Title: [{category_code}-SPEC]{title_format}

## Metadata

**Status**: To Do | In Progress | Blocked | Done

**Parent Epic**: [FEATURE] {{SERVICE_NAME}} - {{FEATURE_DESCRIPTION}} (#{{epic_number}})

**Worktree**: `#{{epic_number}} - {{SERVICE_NAME}} {{FEATURE_DESCRIPTION}}` (inherited from Epic)

---

## Gate Approvers

**Primary**: CTO Agent
**Secondary**: {spec_secondary}
**Gate Type**: Specification Approval Gate

---

## Purpose

{purpose}

---

{phase1}

---

## Definition of Done (SPEC)

- [ ] All Acceptance Criteria checked
- [ ] CTO Agent + secondary approver have approved
- [ ] Ready for [{category_code}-TEST] ticket creation

---

{footer}

## Labels

`{category_code.lower()}, spec, {{service-name}}`

## Links

- Parent: [FEATURE] {{SERVICE_NAME}} – {{FEATURE_DESCRIPTION}}
- Child: [{category_code}-TEST] {{SERVICE_NAME}}...
- Child: [{category_code}-IMPL] {{SERVICE_NAME}}...
```

---

## Notes for Template Users

1. **Completeness**: Ensure all requirements are captured
2. **Clarity**: Use clear, unambiguous language
3. **Scenarios**: Cover all key use cases with Gherkin
4. **Schemas**: Define complete data structures
5. **Dependencies**: List all external dependencies
6. **Questions**: Document all open questions
7. **Approval**: Get explicit approval before proceeding
8. **Traceability**: Link to parent epic

This specification template establishes all requirements before test and implementation work begins.
'''

    return template

def create_test_template(category_code, category_name, source_content, test_primary):
    """Create TEST template"""
    phase2 = extract_phase_content(source_content, 2)
    footer = extract_footer(source_content)
    title_format = get_title_format(source_content, category_code)

    template = f'''# {category_name} Test Template

## Title Format
`[{category_code}-TEST]{title_format}`

---

## Template

```markdown
Title: [{category_code}-TEST]{title_format}

## Metadata

**Status**: To Do | In Progress | Blocked | Done

**Parent Spec**: [{category_code}-SPEC] {{SERVICE_NAME}}... (#{{spec_issue_number}})

**Parent Epic**: [FEATURE] {{SERVICE_NAME}} - {{FEATURE_DESCRIPTION}} (#{{epic_number}})

**Worktree**: `#{{epic_number}} - {{SERVICE_NAME}} {{FEATURE_DESCRIPTION}}` (inherited from Epic)

---

## Gate Approvers

**Primary**: {test_primary}
**Secondary**: CTO Agent
**Gate Type**: Test Completion Gate (tests must run and initially FAIL)

---

## Purpose

Implement comprehensive test suite for {category_name}. Tests cover all scenarios from the specification phase. All tests should initially FAIL as no implementation exists yet (TDD approach).

---

{phase2}

---

## Definition of Done (TEST)

- [ ] All Acceptance Criteria checked
- [ ] All tests written and run (expected to FAIL)
- [ ] Ready for [{category_code}-IMPL] ticket

---

{footer}

## Labels

`{category_code.lower()}, test, {{service-name}}`

## Links

- Parent: [{category_code}-SPEC] {{SERVICE_NAME}}...
- Sibling: [{category_code}-IMPL] {{SERVICE_NAME}}...
- Grandparent: [FEATURE] {{SERVICE_NAME}} – {{FEATURE_DESCRIPTION}}
```

---

## Notes for Template Users

1. **TDD Approach**: Write tests before implementation
2. **Coverage**: Aim for 80%+ test coverage
3. **Scenarios**: Test all Gherkin scenarios from SPEC
4. **Edge Cases**: Test boundary conditions and errors
5. **Fixtures**: Create reusable test fixtures
6. **Mocking**: Mock external dependencies
7. **CI Integration**: Wire tests into CI/CD pipeline
8. **Documentation**: Document test purpose clearly

This test template ensures comprehensive coverage before implementation begins.
'''

    return template

def create_impl_template(category_code, category_name, source_content, impl_primary):
    """Create IMPL template"""
    phase3 = extract_phase_content(source_content, 3)
    footer = extract_footer(source_content)
    title_format = get_title_format(source_content, category_code)

    template = f'''# {category_name} Implementation Template

## Title Format
`[{category_code}-IMPL]{title_format}`

---

## Template

```markdown
Title: [{category_code}-IMPL]{title_format}

## Metadata

**Status**: To Do | In Progress | Blocked | Done

**Parent Spec**: [{category_code}-SPEC] {{SERVICE_NAME}}... (#{{spec_issue_number}})

**Parent Test**: [{category_code}-TEST] {{SERVICE_NAME}}... (#{{test_issue_number}})

**Parent Epic**: [FEATURE] {{SERVICE_NAME}} - {{FEATURE_DESCRIPTION}} (#{{epic_number}})

**Worktree**: `#{{epic_number}} - {{SERVICE_NAME}} {{FEATURE_DESCRIPTION}}` (inherited from Epic)

---

## Gate Approvers

**Primary**: {impl_primary}
**Secondary**: CTO Agent (for code review approval)
**Gate Type**: Implementation Completion Gate + Code Review Gate

---

## Purpose

Implement {category_name} based on the specification and test suite. Implementation must make all tests from [{category_code}-TEST] pass without modification.

---

{phase3}

---

## Definition of Done (IMPL)

- [ ] All Acceptance Criteria checked
- [ ] All tests from [{category_code}-TEST] now PASS
- [ ] Code review approved
- [ ] PR merged

---

{footer}

## Labels

`{category_code.lower()}, implementation, {{service-name}}`

## Links

- Parent: [{category_code}-SPEC] {{SERVICE_NAME}}...
- Sibling: [{category_code}-TEST] {{SERVICE_NAME}}...
- Grandparent: [FEATURE] {{SERVICE_NAME}} – {{FEATURE_DESCRIPTION}}
```

---

## Notes for Template Users

1. **TDD Workflow**: Follow red-green-refactor cycle
2. **Small Commits**: Commit frequently with clear messages
3. **Code Quality**: Run linters and type checkers
4. **No Secrets**: Use environment variables
5. **Error Handling**: Implement comprehensive error handling
6. **Logging**: Add structured logging throughout
7. **Monitoring**: Integrate observability from start
8. **Documentation**: Add docstrings and comments
9. **Review**: Request thorough code review
10. **Testing**: Verify all tests pass before PR

This implementation template provides the foundation for completing the work.
'''

    return template

# Template configurations
templates_config = [
    ('EVENT', 'Event-Driven Architecture', 'Backend Architect Agent OR Platform Engineer', 'QA Engineer OR Backend Developer', 'Backend Developer'),
    ('OBS', 'Observability', 'SRE OR Platform Engineer', 'QA Engineer OR SRE', 'Backend Developer OR SRE'),
    ('API', 'API Development', 'Backend Architect Agent', 'QA Engineer OR Backend Developer', 'Backend Developer'),
    ('DB', 'Database Schema', 'Database Engineer OR Backend Architect', 'QA Engineer OR Backend Developer', 'Backend Developer'),
    ('STATE', 'State Management', 'Frontend Architect OR Backend Developer', 'QA Engineer OR Frontend Developer', 'Frontend Developer OR Backend Developer'),
]

# Process each template
for cat_code, cat_name, spec_secondary, test_primary, impl_primary in templates_config:
    source_file = f'{cat_code}.md'

    if not os.path.exists(source_file):
        print(f'Source file {source_file} not found, skipping...')
        continue

    print(f'Processing {cat_code}...')

    # Read source content
    with open(source_file, 'r') as f:
        content = f.read()

    # Create SPEC template
    spec_content = create_spec_template(cat_code, cat_name, content, spec_secondary)
    with open(f'{cat_code}-SPEC.md', 'w') as f:
        f.write(spec_content)
    print(f'  Created {cat_code}-SPEC.md')

    # Create TEST template
    test_content = create_test_template(cat_code, cat_name, content, test_primary)
    with open(f'{cat_code}-TEST.md', 'w') as f:
        f.write(test_content)
    print(f'  Created {cat_code}-TEST.md')

    # Create IMPL template
    impl_content = create_impl_template(cat_code, cat_name, content, impl_primary)
    with open(f'{cat_code}-IMPL.md', 'w') as f:
        f.write(impl_content)
    print(f'  Created {cat_code}-IMPL.md')

print('\nDone! All templates created.')
print(f'Total .md files: {len([f for f in os.listdir(".") if f.endswith(".md")])}')
